RacesOfValheim/JotunnModStub/RacesOfValheim.cs
kanym cb29f54a28 chore(release): v1.6.2 - race eyes and controller fixes
Version 1.6.2 in the manifests and PluginVersion. README: the New in
v1.6.2 block and the changelog, crediting lexsonn's reports; the Aswid
eyes, Alfar levitation and Geisli lines follow the changes.
2026-10-27 19:36:02 +01:00

1512 lines
76 KiB
C#

using System.Collections;
using BepInEx;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using UnityEngine;
using UnityEngine.UI; // Added for UI
namespace RacesOfValheim
{
[BepInPlugin(PluginGUID, PluginName, PluginVersion)]
[BepInDependency(Jotunn.Main.ModGuid)]
public class RacesOfValheim : BaseUnityPlugin
{
public const string PluginGUID = "com.nandor.racesofvalheim";
public const string PluginName = "Races Of Valheim";
public const string PluginVersion = "1.6.2";
private readonly Harmony harmony = new Harmony(PluginGUID);
public static RacesOfValheim Instance;
private GameObject raceSelectionMenu;
private void Awake() {
Instance = this;
// Bound in alphabetical order by race, since Configuration Manager's category list
// follows bind order rather than sorting itself - confirmed from the Skadi/Aswid
// ordering in-game. Keep new races' Bind() calls slotted in alphabetically here.
AlfarConfig.Bind(Config);
AlfarPowerConfig.Bind(Config);
AlfarNexusConfig.Bind(Config);
AswidConfig.Bind(Config);
DraughConfig.Bind(Config);
DvergarConfigManagement.Bind(Config);
FenrirConfig.Bind(Config);
FurlingConfig.Bind(Config);
SkadiConfig.Bind(Config);
SkeletonConfig.Bind(Config);
SvermConfigManagement.Bind(Config);
TrentaConfigManagement.Bind(Config);
TrolConfig.Bind(Config);
// 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);
// Not a race either: the faction truce and the faction merchants, which cut across
// every race at once, so they bind last rather than inside the alphabetical run above.
FactionsConfig.Bind(Config);
// After every Bind above: tags the gameplay entries for Jotunn's server-to-client sync.
ConfigSync.Apply(Config);
harmony.PatchAll();
gameObject.AddComponent<FenrirRace>();
gameObject.AddComponent<SkadiRace>();
gameObject.AddComponent<SkeletonRace>();
gameObject.AddComponent<AswidRace>();
gameObject.AddComponent<FurlingRace>();
gameObject.AddComponent<TrolRace>();
gameObject.AddComponent<DraughRace>();
gameObject.AddComponent<DvergarRace>();
gameObject.AddComponent<TrentaRace>();
gameObject.AddComponent<SvermRace>();
// Not a race: a perk two races share (Skadi and Trol build inside troll caves), so it
// gets its own component rather than living inside either one's Update.
gameObject.AddComponent<RaceCaveBuilding>();
PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets;
CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand());
CommandManager.Instance.AddConsoleCommand(new CheckProgressionCommand());
CommandManager.Instance.AddConsoleCommand(new IncreaseProgressionCommand());
CommandManager.Instance.AddConsoleCommand(new ResetProgressionCommand());
CommandManager.Instance.AddConsoleCommand(new DumpDvergerCommand());
CommandManager.Instance.AddConsoleCommand(new DumpElderCommand());
CommandManager.Instance.AddConsoleCommand(new DumpGammelCommand());
CommandManager.Instance.AddConsoleCommand(new FenrirPackSpawnCommand());
CommandManager.Instance.AddConsoleCommand(new DumpPotionsCommand());
CommandManager.Instance.AddConsoleCommand(new ListPrefabsCommand());
CommandManager.Instance.AddConsoleCommand(new AlfarProbeCommand());
CommandManager.Instance.AddConsoleCommand(new AlfarStatusCommand());
CommandManager.Instance.AddConsoleCommand(new AlfarResetCommand());
CommandManager.Instance.AddConsoleCommand(new AlfarEitrCommand());
CommandManager.Instance.AddConsoleCommand(new AlfarHpCommand());
CommandManager.Instance.AddConsoleCommand(new DumpAnimCommand());
CommandManager.Instance.AddConsoleCommand(new EvilLaughCommand());
}
/// <summary>
/// Clears the current race and reopens the selection menu. Shared by the resetrace console
/// command and the Race Menu Ward, so both paths clean up exactly the same state.
///
/// Every status effect a race can leave running is removed here, not just the "stats"
/// ones - a cooldown SE left ticking after a reset is invisible until the player picks
/// the same race again and finds an ability still locked out for a timer nobody can see.
/// The item purge runs LAST, after the ZDO already reads "Human": RaceClawSet.For and
/// SvermVisuals.IsSvermPlayer both read the race live off the player, so purging before
/// the race actually changes would find nothing foreign yet.
/// </summary>
public static void ResetRace()
{
Player player = Player.m_localPlayer;
if (player == null) return;
// What the reset actually took off, printed at the end so it can be read in the console.
var removed = new System.Collections.Generic.List<string>();
// Forms first, before any status effect goes. Taking a form's effect away without
// undoing the form leaves the body hidden (bat, mist, drake, wolf, Muspell, Ravager)
// or oversized (True Form), and several races only ever look at their form from an
// Update that returns early for anyone who is not of that race any more.
if (AswidRace.Instance != null && AswidRace.Instance.HardResetForReset()) removed.Add("form: Aswid bat/mist");
if (FenrirRace.Instance != null && FenrirRace.Instance.HardResetForReset()) removed.Add("form: Fenrir");
if (SkadiRace.Instance != null && SkadiRace.Instance.HardResetForReset()) removed.Add("form: Skadi drake");
if (TrolRace.Instance != null && TrolRace.Instance.HardResetForReset()) removed.Add("form: Trol True Form");
if (TrentaMuspell.HardResetForReset(player)) removed.Add("form: Trenta Muspell");
if (SvermRavagerForm.HardResetForReset(player)) removed.Add("form: Sverm Ravager");
RemovePermanentRaceEquipment(player);
player.m_customData.Remove("Race");
player.m_customData.Remove("FenrirCurse_Active");
// Restore original skin color if it exists
if (player.m_customData.ContainsKey("OriginalSkinColor_X"))
{
float x = float.Parse(player.m_customData["OriginalSkinColor_X"]);
float y = float.Parse(player.m_customData["OriginalSkinColor_Y"]);
float z = float.Parse(player.m_customData["OriginalSkinColor_Z"]);
Vector3 origColor = new Vector3(x, y, z);
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq != null)
{
Traverse.Create(visEq).Method("SetSkinColor", origColor).GetValue();
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
}
// Every status effect this mod registers, rather than a list kept by hand: the hand
// list was missing the True Form and both of its cooldowns, Bat and Mist Form, the
// Skeleton's resurrect cooldown and most of Skadi's, and the next effect anyone adds
// would have been missing too. The forms were dropped above, so taking their effects
// away here no longer leaves a body hidden or blown up.
SEMan seman = player.GetSEMan();
foreach (CustomStatusEffect custom in ModRegistry.GetStatusEffects(PluginGUID))
{
StatusEffect se = custom?.StatusEffect;
if (se == null) continue;
int hash = se.name.GetStableHashCode();
if (!seman.HaveStatusEffect(hash)) continue;
seman.RemoveStatusEffect(hash, true);
removed.Add(se.name);
}
// COLD, which is not one of ours at all - and that is exactly why it has to go.
//
// The Aswid does not add a status effect for its night aura; it takes over the vanilla
// Cold that the night hands out anyway. Aswid_ColdStatus_Patch renames the instance to
// "Night Aura" and AswidRace.ApplyNightAuraTint paints its vfx_Cold particles black and
// doubles them, both applied to the LIVE instance hanging off the player and marked
// with NightAuraTintFlag so it is only done once.
//
// Nothing here used to remove it, so the blackened smoke - and the "Night Aura" label -
// simply stayed on through a race change and followed the player onto a Dvergar. There
// is no untinting it: the original colours and emission rates were never recorded. So
// the instance goes, and the night hands out a fresh, ordinary Cold within moments -
// this time with nobody left to rename or repaint it.
player.GetSEMan().RemoveStatusEffect("Cold".GetStableHashCode());
// BURNING, the same story: Through Fire and Flames is vanilla's Burning set to 999
// minutes, and it followed the player onto whatever race came next.
FurlingFireAbility.RemovePermanentBurning(player);
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Human");
// Only after the ZDO above already says "Human" - see the class doc comment.
RaceItemCleanup.PurgeForeignRaceItems(player);
// Normal size. The Trol, the Skeleton past Fader and the self-sizing races all scale
// either the player or its Visual, and each puts its own size back only from code that
// may not run again now the race has changed. The next race sets its own size anyway.
player.transform.localScale = Vector3.one;
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
if (visual != null) visual.transform.localScale = Vector3.one;
string summary = removed.Count == 0
? "[ResetRace] Nothing race-specific was left on the player."
: "[ResetRace] Removed: " + string.Join(", ", removed);
Jotunn.Logger.LogInfo(summary);
if (Console.instance != null) Console.instance.Print(summary);
if (Instance != null)
{
Instance.ShowRaceSelectionMenu();
}
}
/// <summary>
/// Gives back the progression a player claimed for themselves, and says plainly when there
/// is none to give back. Shared by the resetprogression console command and the Race Menu
/// Ward's Reset Progression button.
///
/// This used to clear BossProgressionManager.DebugState and nothing else - the console-only
/// debug override, a static that is -1 at every launch and that the ward never writes. The
/// two things the ward DOES write, RacesOfValheim_PersonalState and _PersonalMode in
/// m_customData, were untouched, so for anyone who had not just typed increaseprogression
/// in this session the button was a no-op by construction. It then reported
/// GetCurrentProgressionState() as the result, which is the unchanged current tier - the
/// "it always puts me back at the tier I'm on" the testers were describing. They were
/// reading the one number that function could possibly have produced.
///
/// What it resets now is the personal tier only. The progression MODE is deliberately left
/// alone: a player who chose to be independent of the server's kills stays independent,
/// they just start claiming relics again from the bottom. And world progression is not this
/// button's to reset - those are the world's global keys, shared by everyone on the server -
/// so in world mode it says so rather than pretending.
/// </summary>
/// <param name="summary">Human-readable account of what actually changed, for the console.</param>
public static int ResetProgression(out string summary)
{
// Still cleared, and first: it outranks both of the others in
// GetCurrentProgressionState, so leaving it up would mask whatever we do below.
bool hadDebugOverride = BossProgressionManager.DebugState != -1;
BossProgressionManager.DebugState = -1;
bool clearedPersonal = false;
if (BossProgressionManager.UsePersonalProgression && BossProgressionManager.HasPersonalState)
{
BossProgressionManager.ClearPersonalState();
clearedPersonal = true;
}
int state = BossProgressionManager.GetCurrentProgressionState();
string boss = BossProgressionManager.GetBossTokenForState(state);
if (clearedPersonal)
summary = ModText.Get("rov_msg_core_progression_reset", boss, state, BossProgressionManager.MaxState);
else if (BossProgressionManager.UsePersonalProgression)
summary = ModText.Get("rov_msg_core_nothing_reset_personal", state, BossProgressionManager.MaxState);
else
summary = ModText.Get("rov_msg_core_nothing_reset_world", boss, state, BossProgressionManager.MaxState);
if (hadDebugOverride) summary += " " + ModText.Get("rov_msg_core_debug_override_cleared");
Player player = Player.m_localPlayer;
if (player != null)
{
player.Message(MessageHud.MessageType.Center, summary);
// Progression drives stats and unlocks that are only recalculated when equipment is
// set up, so nudge that or the new tier will not show until something else does.
Traverse.Create(player).Method("SetupEquipment").GetValue();
}
return state;
}
/// <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();
FenrirRace.Instance.CreateModAssets();
SkadiRace.Instance.CreateModAssets();
SkeletonRace.Instance.CreateModAssets();
AswidRace.Instance.CreateModAssets();
FurlingRace.Instance.CreateModAssets();
TrolRace.Instance.CreateModAssets();
DraughRace.Instance.CreateModAssets();
DvergarRace.Instance.CreateModAssets();
TrentaRace.Instance.CreateModAssets();
SvermRace.Instance.CreateModAssets();
AlfarRace.CreateModAssets();
WarVultureItem.Register();
TrolsHammerItem.Register();
BoneServant.Register();
}
// --- RACE SELECTION UI ---
public void ShowRaceSelectionMenu()
{
if (raceSelectionMenu != null) return;
if (GUIManager.Instance == null || GUIManager.CustomGUIFront == null)
{
Jotunn.Logger.LogWarning("GUIManager.CustomGUIFront is null, cannot show race menu.");
return;
}
raceSelectionMenu = new GameObject("RaceSelectionMenu");
raceSelectionMenu.transform.SetParent(GUIManager.CustomGUIFront.transform, false);
RectTransform rect = raceSelectionMenu.AddComponent<RectTransform>();
rect.anchorMin = new Vector2(0, 0);
rect.anchorMax = new Vector2(1, 1);
rect.offsetMin = Vector2.zero;
rect.offsetMax = Vector2.zero;
Image bg = raceSelectionMenu.AddComponent<Image>();
bg.color = new Color(0, 0, 0, 0.9f);
GameObject selectionPanel = new GameObject("SelectionPanel");
selectionPanel.transform.SetParent(raceSelectionMenu.transform, false);
RectTransform spRect = selectionPanel.AddComponent<RectTransform>();
spRect.anchorMin = Vector2.zero; spRect.anchorMax = Vector2.one;
spRect.offsetMin = Vector2.zero; spRect.offsetMax = Vector2.zero;
GameObject confirmationPanel = new GameObject("ConfirmationPanel");
confirmationPanel.transform.SetParent(raceSelectionMenu.transform, false);
RectTransform cpRect = confirmationPanel.AddComponent<RectTransform>();
cpRect.anchorMin = Vector2.zero; cpRect.anchorMax = Vector2.one;
cpRect.offsetMin = Vector2.zero; cpRect.offsetMax = Vector2.zero;
confirmationPanel.SetActive(false);
GameObject titleObj = new GameObject("Title");
titleObj.transform.SetParent(selectionPanel.transform, false);
Text titleText = titleObj.AddComponent<Text>();
titleText.font = GUIManager.Instance.AveriaSerifBold;
titleText.text = ModText.Get("rov_menu_choose_race");
titleText.fontSize = 50;
titleText.alignment = TextAnchor.MiddleCenter;
titleText.color = Color.white;
RectTransform titleRect = titleObj.GetComponent<RectTransform>();
titleRect.anchoredPosition = new Vector2(0, 200);
titleRect.sizeDelta = new Vector2(600, 100);
GameObject confTitleObj = new GameObject("ConfTitle");
confTitleObj.transform.SetParent(confirmationPanel.transform, false);
Text confTitleText = confTitleObj.AddComponent<Text>();
confTitleText.font = GUIManager.Instance.AveriaSerifBold;
confTitleText.fontSize = 50;
confTitleText.alignment = TextAnchor.MiddleCenter;
confTitleText.color = Color.white;
RectTransform confTitleRect = confTitleObj.GetComponent<RectTransform>();
confTitleRect.anchoredPosition = new Vector2(0, 150);
confTitleRect.sizeDelta = new Vector2(600, 100);
GameObject confDescObj = new GameObject("ConfDesc");
confDescObj.transform.SetParent(confirmationPanel.transform, false);
Text confDescText = confDescObj.AddComponent<Text>();
confDescText.font = GUIManager.Instance.AveriaSerifBold;
confDescText.fontSize = 24;
confDescText.alignment = TextAnchor.MiddleCenter;
confDescText.color = Color.white;
RectTransform confDescRect = confDescObj.GetComponent<RectTransform>();
confDescRect.anchoredPosition = new Vector2(0, 0);
confDescRect.sizeDelta = new Vector2(800, 200);
GameObject btnOkObj = new GameObject("OkButton");
btnOkObj.transform.SetParent(confirmationPanel.transform, false);
RectTransform btnOkRect = btnOkObj.AddComponent<RectTransform>();
btnOkRect.sizeDelta = new Vector2(200, 60);
btnOkRect.anchoredPosition = new Vector2(120, -150);
Image btnOkImg = btnOkObj.AddComponent<Image>();
btnOkImg.color = new Color(0.2f, 0.5f, 0.2f, 1f);
Button btnOk = btnOkObj.AddComponent<Button>();
GameObject btnOkTxtObj = new GameObject("Text");
btnOkTxtObj.transform.SetParent(btnOkObj.transform, false);
Text btnOkTxt = btnOkTxtObj.AddComponent<Text>();
btnOkTxt.font = GUIManager.Instance.AveriaSerifBold;
btnOkTxt.text = ModText.Get("rov_menu_ok");
btnOkTxt.fontSize = 24;
btnOkTxt.alignment = TextAnchor.MiddleCenter;
btnOkTxt.color = Color.white;
RectTransform btnOkTxtRect = btnOkTxtObj.GetComponent<RectTransform>();
btnOkTxtRect.anchorMin = Vector2.zero; btnOkTxtRect.anchorMax = Vector2.one;
btnOkTxtRect.offsetMin = Vector2.zero; btnOkTxtRect.offsetMax = Vector2.zero;
GameObject btnBackObj = new GameObject("BackButton");
btnBackObj.transform.SetParent(confirmationPanel.transform, false);
RectTransform btnBackRect = btnBackObj.AddComponent<RectTransform>();
btnBackRect.sizeDelta = new Vector2(200, 60);
btnBackRect.anchoredPosition = new Vector2(-120, -150);
Image btnBackImg = btnBackObj.AddComponent<Image>();
btnBackImg.color = new Color(0.5f, 0.2f, 0.2f, 1f);
Button btnBack = btnBackObj.AddComponent<Button>();
btnBack.onClick.AddListener(() => {
confirmationPanel.SetActive(false);
selectionPanel.SetActive(true);
});
GameObject btnBackTxtObj = new GameObject("Text");
btnBackTxtObj.transform.SetParent(btnBackObj.transform, false);
Text btnBackTxt = btnBackTxtObj.AddComponent<Text>();
btnBackTxt.font = GUIManager.Instance.AveriaSerifBold;
btnBackTxt.text = ModText.Get("rov_menu_back");
btnBackTxt.fontSize = 24;
btnBackTxt.alignment = TextAnchor.MiddleCenter;
btnBackTxt.color = Color.white;
RectTransform btnBackTxtRect = btnBackTxtObj.GetComponent<RectTransform>();
btnBackTxtRect.anchorMin = Vector2.zero; btnBackTxtRect.anchorMax = Vector2.one;
btnBackTxtRect.offsetMin = Vector2.zero; btnBackTxtRect.offsetMax = Vector2.zero;
// The race ID picks the texts and is what gets saved; the button, the title and the
// description only ever show the translated name. See ModText.RaceName for why the two
// must never be the same string.
void CreateRaceButtonWithConfirm(string raceId, Vector2 position, Sprite iconSprite, UnityEngine.Events.UnityAction onConfirm, params object[] descArgs)
{
string name = ModText.RaceName(raceId);
CreateRaceButton(raceId, name, position, iconSprite, selectionPanel.transform, () => {
selectionPanel.SetActive(false);
confirmationPanel.SetActive(true);
confTitleText.text = name;
confDescText.text = ModText.RaceDescription(raceId, descArgs);
btnOk.onClick.RemoveAllListeners();
btnOk.onClick.AddListener(onConfirm);
});
}
// Row 1 (y = 100)
CreateRaceButtonWithConfirm("Human", new Vector2(-450, 100), GetHumanIcon(), SelectHuman);
CreateRaceButtonWithConfirm("Fenrir", new Vector2(-150, 100), GetFenrirIcon(), SelectFenrir);
CreateRaceButtonWithConfirm("Skadi", new Vector2(150, 100), GetSkadiIcon(), SelectSkadi);
CreateRaceButtonWithConfirm(SkeletonVisuals.RaceId, new Vector2(450, 100), GetSkeletonIcon(), SelectSkeleton);
// Row 2 (y = -20)
CreateRaceButtonWithConfirm("Aswid", new Vector2(-450, -20), GetAswidIcon(), SelectAswid);
CreateRaceButtonWithConfirm("Furling", new Vector2(-150, -20), GetFurlingIcon(), SelectFurling);
// $1 in the Trol's description is how much harder fire burns it, read from the config.
CreateRaceButtonWithConfirm("Trol", new Vector2(150, -20), GetTrolIcon(), SelectTrol,
((TrolConfig.FireWeaknessMultiplier.Value - 1f) * 100f).ToString("0"));
CreateRaceButtonWithConfirm(DraughVisuals.RaceId, new Vector2(450, -20), GetDraughIcon(), SelectDraugh);
// Row 3 (y = -140)
CreateRaceButtonWithConfirm(DvergarConfig.RaceId, new Vector2(-450, -140), GetDvergarIcon(), SelectDvergar);
CreateRaceButtonWithConfirm(TrentaConfig.RaceId, new Vector2(-150, -140), GetTrentaIcon(), SelectTrenta);
CreateRaceButtonWithConfirm(SvermConfig.RaceId, new Vector2(150, -140), GetSvermIcon(), SelectSverm);
CreateRaceButtonWithConfirm(AlfarConfig.RaceId, new Vector2(450, -140), GetAlfarIcon(), SelectAlfar);
GUIManager.BlockInput(true);
}
/// <summary>
/// The icon the race menu shows for a race, for anything else that names a race - the race
/// requirement in the build panel (RaceStationLock). One source, so the two never disagree.
/// </summary>
public static Sprite RaceIcon(string race)
{
if (Instance == null || string.IsNullOrEmpty(race)) return null;
switch (race)
{
case "Fenrir": return Instance.GetFenrirIcon();
case "Skadi": return Instance.GetSkadiIcon();
case SkeletonVisuals.RaceId: return Instance.GetSkeletonIcon();
case "Aswid": return Instance.GetAswidIcon();
case "Furling": return Instance.GetFurlingIcon();
case "Trol": return Instance.GetTrolIcon();
case DvergarConfig.RaceId: return Instance.GetDvergarIcon();
case TrentaConfig.RaceId: return Instance.GetTrentaIcon();
case SvermConfig.RaceId: return Instance.GetSvermIcon();
case AlfarConfig.RaceId: return Instance.GetAlfarIcon();
}
return race == DraughVisuals.RaceId ? Instance.GetDraughIcon() : Instance.GetHumanIcon();
}
private Sprite GetHumanIcon()
{
GameObject clubPrefab = PrefabManager.Cache.GetPrefab<ItemDrop>("Club")?.gameObject;
if (clubPrefab != null)
{
ItemDrop clubDrop = clubPrefab.GetComponent<ItemDrop>();
if (clubDrop != null && clubDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return clubDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private Sprite GetFenrirIcon()
{
GameObject fenringTrophy = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyFenring")?.gameObject;
if (fenringTrophy != null)
{
ItemDrop trophyDrop = fenringTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private Sprite GetSkadiIcon()
{
GameObject drakeTrophy = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyHatchling")?.gameObject;
if (drakeTrophy != null)
{
ItemDrop trophyDrop = drakeTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private Sprite GetSkeletonIcon()
{
GameObject skelTrophy = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySkeleton")?.gameObject;
if (skelTrophy != null)
{
ItemDrop trophyDrop = skelTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private Sprite GetAswidIcon()
{
GameObject aswidTrophy = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyWraith")?.gameObject;
if (aswidTrophy != null)
{
ItemDrop trophyDrop = aswidTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private void CreateRaceButton(string raceId, string label, Vector2 position, Sprite iconSprite, Transform parentTransform, UnityEngine.Events.UnityAction onClick)
{
GameObject btnObj = new GameObject(raceId + "Button");
btnObj.transform.SetParent(parentTransform, false);
RectTransform btnRect = btnObj.AddComponent<RectTransform>();
btnRect.sizeDelta = new Vector2(250, 80);
btnRect.anchoredPosition = position;
Image btnImg = btnObj.AddComponent<Image>();
btnImg.color = new Color(0.2f, 0.2f, 0.2f, 1f);
Button btn = btnObj.AddComponent<Button>();
btn.onClick.AddListener(onClick);
GameObject txtObj = new GameObject("Text");
txtObj.transform.SetParent(btnObj.transform, false);
Text txt = txtObj.AddComponent<Text>();
txt.font = GUIManager.Instance.AveriaSerifBold;
txt.text = label;
txt.fontSize = 30;
txt.alignment = TextAnchor.MiddleCenter;
txt.color = Color.white;
RectTransform txtRect = txtObj.GetComponent<RectTransform>();
txtRect.anchorMin = Vector2.zero;
txtRect.anchorMax = Vector2.one;
txtRect.offsetMin = Vector2.zero;
txtRect.offsetMax = Vector2.zero;
if (iconSprite != null)
{
GameObject iconObj = new GameObject("Icon");
iconObj.transform.SetParent(btnObj.transform, false);
Image iconImg = iconObj.AddComponent<Image>();
iconImg.sprite = iconSprite;
RectTransform iconRect = iconObj.GetComponent<RectTransform>();
iconRect.sizeDelta = new Vector2(60, 60);
iconRect.anchoredPosition = new Vector2(-70, 0); // shift left
txt.alignment = TextAnchor.MiddleRight;
txtRect.offsetMax = new Vector2(-30, 0);
}
}
private void SelectHuman()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Human";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Human");
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_remain_human"));
}
CloseRaceSelectionMenu();
}
private void SelectFenrir()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Fenrir";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Fenrir");
Player.m_localPlayer.m_customData["FenrirCurse_Active"] = "true";
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_FenrirCurse".GetStableHashCode(), true);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_fenrir"));
}
CloseRaceSelectionMenu();
}
private void SelectSkadi()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Skadi";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Skadi");
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_skadi"));
// Force update skin colors
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
}
CloseRaceSelectionMenu();
}
private void SelectSkeleton()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Skeleton";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Skeleton");
// Add the stats SE for Skeleton
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_SkeletonStats".GetStableHashCode(), true);
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_skeleton"));
CloseRaceSelectionMenu();
}
}
private void SelectAswid()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Aswid";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Aswid");
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
// Save original skin color
if (!Player.m_localPlayer.m_customData.ContainsKey("OriginalSkinColor_X"))
{
Vector3 currentSkinColor = Traverse.Create(visEq).Field("m_skinColor").GetValue<Vector3>();
Player.m_localPlayer.m_customData["OriginalSkinColor_X"] = currentSkinColor.x.ToString();
Player.m_localPlayer.m_customData["OriginalSkinColor_Y"] = currentSkinColor.y.ToString();
Player.m_localPlayer.m_customData["OriginalSkinColor_Z"] = currentSkinColor.z.ToString();
}
// Force max white
Traverse.Create(visEq).Method("SetSkinColor", new Vector3(1f, 1f, 1f)).GetValue();
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_aswid"));
CloseRaceSelectionMenu();
}
}
private void SelectFurling()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Furling";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Furling");
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
if (!Player.m_localPlayer.m_customData.ContainsKey("OriginalSkinColor_X"))
{
Vector3 currentSkinColor = Traverse.Create(visEq).Field("m_skinColor").GetValue<Vector3>();
Player.m_localPlayer.m_customData["OriginalSkinColor_X"] = currentSkinColor.x.ToString();
Player.m_localPlayer.m_customData["OriginalSkinColor_Y"] = currentSkinColor.y.ToString();
Player.m_localPlayer.m_customData["OriginalSkinColor_Z"] = currentSkinColor.z.ToString();
}
Traverse.Create(visEq).Method("SetSkinColor", new Vector3(0.3f, 0.8f, 0.3f)).GetValue();
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_furling"));
CloseRaceSelectionMenu();
}
}
private Sprite GetFurlingIcon()
{
GameObject trophyPrefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyGoblin")?.gameObject;
if (trophyPrefab != null)
{
ItemDrop trophyDrop = trophyPrefab.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private void SelectTrol()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Trol";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Trol");
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
if (!Player.m_localPlayer.m_customData.ContainsKey("OriginalSkinColor_X"))
{
Vector3 currentSkinColor = Traverse.Create(visEq).Field("m_skinColor").GetValue<Vector3>();
Player.m_localPlayer.m_customData["OriginalSkinColor_X"] = currentSkinColor.x.ToString();
Player.m_localPlayer.m_customData["OriginalSkinColor_Y"] = currentSkinColor.y.ToString();
Player.m_localPlayer.m_customData["OriginalSkinColor_Z"] = currentSkinColor.z.ToString();
}
Traverse.Create(visEq).Method("SetSkinColor", new Vector3(0.1f, 0.6f, 0.7f)).GetValue();
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_trol"));
CloseRaceSelectionMenu();
}
}
private Sprite GetTrolIcon()
{
GameObject trophyPrefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyFrostTroll")?.gameObject;
// TrophyForestTroll, not "TrophyTroll": the latter is not a prefab in this game, so the
// fallback could never fire and the name sat here as a free slot for any mod that
// happens to ship one. See SkeletonVisuals.EnsureFireAura for what that costs.
if (trophyPrefab == null) trophyPrefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyForestTroll")?.gameObject;
if (trophyPrefab != null)
{
ItemDrop trophyDrop = trophyPrefab.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private void SelectDraugh()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Draugh";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Draugh");
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
if (!Player.m_localPlayer.m_customData.ContainsKey("OriginalSkinColor_X"))
{
Vector3 currentSkinColor = Traverse.Create(visEq).Field("m_skinColor").GetValue<Vector3>();
Player.m_localPlayer.m_customData["OriginalSkinColor_X"] = currentSkinColor.x.ToString();
Player.m_localPlayer.m_customData["OriginalSkinColor_Y"] = currentSkinColor.y.ToString();
Player.m_localPlayer.m_customData["OriginalSkinColor_Z"] = currentSkinColor.z.ToString();
}
Traverse.Create(visEq).Method("SetSkinColor", new Vector3(0.25f, 0.4f, 0.28f)).GetValue();
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_draugh"));
CloseRaceSelectionMenu();
}
}
private Sprite GetDraughIcon()
{
GameObject trophyPrefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyDraugr")?.gameObject;
if (trophyPrefab != null)
{
ItemDrop trophyDrop = trophyPrefab.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private void SelectDvergar()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = DvergarConfig.RaceId;
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", DvergarConfig.RaceId);
Player.m_localPlayer.GetSEMan().AddStatusEffect(DvergarConfig.StatsSE.GetStableHashCode(), true);
// No SetSkinColor here: the tint is written onto the material by the UpdateColors
// postfix in DvergarPatches, which keys off the race and so needs nothing saved.
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
visEq.GetType().GetMethod("UpdateVisuals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_dvergar"));
CloseRaceSelectionMenu();
}
}
private void SelectSverm()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = SvermConfig.RaceId;
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", SvermConfig.RaceId);
Player.m_localPlayer.GetSEMan().AddStatusEffect(SvermConfig.StatsSE.GetStableHashCode(), true);
// The carapace seals chest, legs and helmet, so whatever the player was wearing in
// those slots has to come off before the visual rebuild - otherwise the old chest
// stays on screen underneath a carapace that the equip patch will refuse to remove
// later, because the refusal is on EQUIPPING, not on unequipping.
Humanoid humanoid = Player.m_localPlayer;
foreach (ItemDrop.ItemData.ItemType slot in SvermConfig.SealedSlots)
{
ItemDrop.ItemData worn = null;
foreach (ItemDrop.ItemData item in humanoid.GetInventory().GetEquippedItems())
{
if (item != null && item.m_shared != null && item.m_shared.m_itemType == slot) { worn = item; break; }
}
if (worn != null) humanoid.UnequipItem(worn, false);
}
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
visEq.GetType().GetMethod("UpdateVisuals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_sverm"));
CloseRaceSelectionMenu();
}
}
private void SelectAlfar()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = AlfarConfig.RaceId;
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", AlfarConfig.RaceId);
// The grey skin is written by Alfar_UpdateColors_Patch, which runs after UpdateColors:
// push one through so the change shows now and not at the next visual refresh.
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null) Traverse.Create(visEq).Method("UpdateColors").GetValue();
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_alfar"));
CloseRaceSelectionMenu();
}
}
/// <summary>
/// Refined eitr's own icon: the race lives on eitr. Falls back to a Surtling core and then
/// to copper so the button is never an empty square.
/// </summary>
private Sprite GetAlfarIcon()
{
GameObject prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("Eitr")?.gameObject;
if (prefab == null) prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("SurtlingCore")?.gameObject;
if (prefab == null) prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("Copper")?.gameObject;
if (prefab != null)
{
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0)
{
return drop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private Sprite GetSvermIcon()
{
GameObject prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySeekerBrute")?.gameObject;
if (prefab == null) prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySeeker")?.gameObject;
if (prefab == null) prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("Chitin")?.gameObject;
if (prefab != null)
{
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0)
{
return drop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private Sprite GetDvergarIcon()
{
GameObject prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("HelmetDverger")?.gameObject;
if (prefab == null) prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("DvergrKeyFragment")?.gameObject;
if (prefab == null) prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("Copper")?.gameObject;
if (prefab != null)
{
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0)
{
return drop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private void SelectTrenta()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = TrentaConfig.RaceId;
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", TrentaConfig.RaceId);
Player.m_localPlayer.GetSEMan().AddStatusEffect(TrentaConfig.StatsSE.GetStableHashCode(), true);
// No SetSkinColor here: the tint is written onto the material by the UpdateColors
// postfix in TrentaPatches, which keys off the race and so needs nothing saved.
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_chose_path_trenta"));
CloseRaceSelectionMenu();
}
}
private Sprite GetTrentaIcon()
{
GameObject prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyGreydwarfBrute")?.gameObject;
if (prefab == null) prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("Wood")?.gameObject;
if (prefab != null)
{
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0)
{
return drop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
public void CloseRaceSelectionMenu()
{
if (raceSelectionMenu != null)
{
Destroy(raceSelectionMenu);
raceSelectionMenu = null;
}
GUIManager.BlockInput(false);
}
}
// --- MAIN MENU CHARACTER PREVIEW SKIN PATCH ---
// Forces skin color/visuals refresh on the FejdStartup character preview
// so Aswid/Furling skins are visible before loading into a world.
[HarmonyPatch(typeof(FejdStartup), "SetupCharacterPreview")]
public static class FejdStartup_SetupCharacterPreview_Patch
{
public static void Postfix(FejdStartup __instance) => ForcePreviewRefresh(__instance);
internal static void ForcePreviewRefresh(FejdStartup instance)
{
// GetPreviewPlayer returns the preview Player instance (has m_customData but no ZNetView)
Player preview = instance.GetType()
.GetMethod("GetPreviewPlayer",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Public)
?.Invoke(instance, null) as Player;
if (preview == null) return;
VisEquipment visEq = preview.GetComponent<VisEquipment>();
if (visEq == null) return;
// Fire UpdateVisuals first (goblin head, hair/beard hide), then UpdateColors (skin tint)
var flags = System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Public;
visEq.GetType().GetMethod("UpdateVisuals", flags)?.Invoke(visEq, null);
visEq.GetType().GetMethod("UpdateColors", flags)?.Invoke(visEq, null);
}
}
[HarmonyPatch(typeof(FejdStartup), "SetSelectedProfile")]
public static class FejdStartup_SetSelectedProfile_Patch
{
public static void Postfix(FejdStartup __instance) =>
FejdStartup_SetupCharacterPreview_Patch.ForcePreviewRefresh(__instance);
}
// --- PLAYER SPAWN PATCH (RACE CHECK) ---
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class PlayerSpawnPatch
{
public static void Postfix(Player __instance)
{
if (__instance == Player.m_localPlayer)
{
// Runs before anything reads the race, so the rest of this method - and the race
// check further down that would otherwise reopen the selection menu - sees the
// renamed id rather than the old one.
DvergarRace.MigrateLegacyRaceId(__instance);
if (__instance.m_customData.ContainsKey("FenrirCurse_Active") && __instance.m_customData["FenrirCurse_Active"] == "true")
{
__instance.GetSEMan().AddStatusEffect("SE_FenrirCurse".GetStableHashCode(), true);
}
// If Skadi, Aswid, Furling, Trol or Draugh, re-trigger visual update to set skin color
if (__instance.m_customData.ContainsKey("Race") && (__instance.m_customData["Race"] == "Skadi" || __instance.m_customData["Race"] == "Aswid" || __instance.m_customData["Race"] == "Furling" || __instance.m_customData["Race"] == "Trol" || __instance.m_customData["Race"] == "Draugh"))
{
VisEquipment visEq = __instance.GetComponent<VisEquipment>();
if (visEq != null) visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
// The Dvergar needs no entry here: its tint is applied by the UpdateColors postfix
// every time Valheim refreshes the body, rather than being stored on the player.
// Heals a save that got stuck holding another race's permanent claws BEFORE this
// purge existed - runs on every spawn rather than only from ResetRace, so a
// player who already has the bug is fixed by logging in, not by finding the Ward
// and resetting a race they may not even want to leave.
RaceItemCleanup.PurgeForeignRaceItems(__instance);
// Check for Race Selection
if (!__instance.m_customData.ContainsKey("Race"))
{
if (RacesOfValheim.Instance != null)
{
RacesOfValheim.Instance.ShowRaceSelectionMenu();
}
}
}
}
}
// --- CONSOLE COMMANDS ---
public class ResetRaceCommand : ConsoleCommand
{
public override string Name => "resetrace";
public override string Help => "Resets the player's race and reopens the race selection menu for debugging";
public override void Run(string[] args)
{
if (Player.m_localPlayer != null)
{
RacesOfValheim.ResetRace();
Console.instance.Print("Race has been reset. The selection menu should now appear.");
}
else
{
Console.instance.Print("You must be in-game to reset your race.");
}
}
}
public class CheckProgressionCommand : ConsoleCommand
{
public override string Name => "checkprogression";
public override string Help => "Checks the current boss progression state (1-8)";
public override void Run(string[] args)
{
int state = BossProgressionManager.GetCurrentProgressionState();
Console.instance.Print($"Current World Boss Progression State: {state}");
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_world_progression_state", state));
}
}
}
public class IncreaseProgressionCommand : ConsoleCommand
{
public override string Name => "increaseprogression";
public override string Help => "[DEBUG] Increases the current boss progression state by 1 (max 8)";
public override void Run(string[] args)
{
if (BossProgressionManager.DebugState == -1)
{
BossProgressionManager.DebugState = BossProgressionManager.GetCurrentProgressionState();
}
if (BossProgressionManager.DebugState < 8)
{
BossProgressionManager.DebugState++;
Console.instance.Print($"[DEBUG] Progression state increased to: {BossProgressionManager.DebugState}");
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_core_progression_state", BossProgressionManager.DebugState));
Traverse.Create(Player.m_localPlayer).Method("SetupEquipment").GetValue();
}
}
else
{
Console.instance.Print("[DEBUG] Progression state is already at maximum (8).");
}
}
}
/// <summary>
/// Dumps the Dvergr NPC prefab: its transform tree, every renderer on it, and its per-star
/// LevelEffects colours. Prefab contents live in the asset bundles and cannot be read outside
/// a running game, so this is how the hood mesh and the star tints get identified.
/// </summary>
public class DumpDvergerCommand : ConsoleCommand
{
public override string Name => "dumpdverger";
public override string Help => "[DEBUG] Logs the Dverger prefab hierarchy, renderers and star colours";
public override void Run(string[] args)
{
string prefabName = args.Length > 0 ? args[0] : DvergarConfig.DvergerPrefabName;
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
if (prefab == null)
{
Console.instance.Print($"Prefab '{prefabName}' not found.");
return;
}
Jotunn.Logger.LogInfo($"=== {prefabName} HIERARCHY ===");
DumpTransform(prefab.transform, "");
// Submeshes and their materials are the part that matters: the Dvergr carries its hood,
// body and clothes in one mesh, so the hood can only be picked out by submesh index.
Jotunn.Logger.LogInfo($"=== {prefabName} RENDERERS ===");
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(true))
{
Mesh mesh = null;
if (renderer is SkinnedMeshRenderer skinned) mesh = skinned.sharedMesh;
else
{
MeshFilter filter = renderer.GetComponent<MeshFilter>();
if (filter != null) mesh = filter.sharedMesh;
}
Jotunn.Logger.LogInfo(
$" {renderer.gameObject.name} ({renderer.GetType().Name}) " +
$"submeshes={(mesh != null ? mesh.subMeshCount : 0)} path={GetPath(renderer.transform)}");
Material[] materials = renderer.sharedMaterials;
for (int i = 0; i < materials.Length; i++)
{
int tris = (mesh != null && i < mesh.subMeshCount) ? mesh.GetTriangles(i).Length / 3 : 0;
Jotunn.Logger.LogInfo($" submesh {i}: material='{(materials[i] != null ? materials[i].name : "null")}' triangles={tris}");
}
}
LevelEffects levelEffects = prefab.GetComponentInChildren<LevelEffects>(true);
if (levelEffects != null && levelEffects.m_levelSetups != null)
{
Jotunn.Logger.LogInfo($"=== {prefabName} LEVEL SETUPS (index 0 = 1 star) ===");
for (int i = 0; i < levelEffects.m_levelSetups.Count; i++)
{
var setup = levelEffects.m_levelSetups[i];
if (setup == null) continue;
Jotunn.Logger.LogInfo(
$" [{i}] scale={setup.m_scale} hue={setup.m_hue} sat={setup.m_saturation} val={setup.m_value} " +
$"emissive={setup.m_setEmissiveColor}:{setup.m_emissiveColor}");
}
}
else
{
Jotunn.Logger.LogInfo($"{prefabName} has no LevelEffects.");
}
Console.instance.Print($"Dumped '{prefabName}' to the BepInEx log.");
}
private static void DumpTransform(Transform t, string indent)
{
if (t == null) return;
System.Text.StringBuilder components = new System.Text.StringBuilder();
foreach (Component c in t.GetComponents<Component>())
{
if (c != null) components.Append(c.GetType().Name).Append(" ");
}
Jotunn.Logger.LogInfo($"{indent}{t.name} [{components}]");
for (int i = 0; i < t.childCount; i++) DumpTransform(t.GetChild(i), indent + " ");
}
private static string GetPath(Transform t)
{
string path = t.name;
while (t.parent != null)
{
t = t.parent;
path = t.name + "/" + path;
}
return path;
}
}
/// <summary>
/// [DEBUG] Built for Muspell (Trenta/Fader): dumps everything about "gd_king" (The Elder) that
/// Mono.Cecil cannot see, since that only reveals field/method *names*, never the actual
/// values baked into the prefab asset. Three things a transformation ability needs and can
/// only get from a live prefab reference:
/// - the full hierarchy (same as DumpDvergerCommand), to see whether "Visual" actually
/// carries the Animator our clone needs, or whether it lives somewhere else;
/// - every Animator's real parameter list, since a wrong trigger name passed to
/// Animator.SetTrigger doesn't throw or warn, it just silently does nothing;
/// - the real attack animation trigger names, read directly off Humanoid.m_defaultItems'
/// weapon SharedData (confirmed via IL that Attack.Start feeds m_attackAnimation straight
/// into ZSyncAnimation.SetTrigger, so this is the actual string The Elder itself uses,
/// not a guess).
/// None of this instantiates the prefab, so nothing here can trigger its AI/Awake logic.
/// </summary>
public class DumpElderCommand : ConsoleCommand
{
public override string Name => "dumpelder";
public override string Help => "[DEBUG] Logs The Elder's hierarchy, Animator parameters and real attack animation names";
public override void Run(string[] args)
{
string prefabName = args.Length > 0 ? args[0] : TrentaConfig.MuspellFormPrefab;
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
if (prefab == null)
{
Console.instance.Print($"Prefab '{prefabName}' not found.");
return;
}
Jotunn.Logger.LogInfo($"=== {prefabName} HIERARCHY ===");
DumpTransform(prefab.transform, "");
Jotunn.Logger.LogInfo($"=== {prefabName} ANIMATORS ===");
bool anyAnimator = false;
foreach (Animator animator in prefab.GetComponentsInChildren<Animator>(true))
{
anyAnimator = true;
Jotunn.Logger.LogInfo($" Animator on '{GetPath(animator.transform)}' controller='{(animator.runtimeAnimatorController != null ? animator.runtimeAnimatorController.name : "null")}'");
if (animator.runtimeAnimatorController == null) continue;
foreach (AnimatorControllerParameter param in animator.parameters)
{
Jotunn.Logger.LogInfo($" param: {param.name} ({param.type})");
}
// Every clip the controller can play. Parameters only say what CAN be driven,
// not what actually exists to play - a wrong trigger name silently plays nothing,
// so this is the list to check a guessed name against.
foreach (AnimationClip clip in animator.runtimeAnimatorController.animationClips)
{
if (clip != null) Jotunn.Logger.LogInfo($" clip: {clip.name}");
}
}
if (!anyAnimator) Jotunn.Logger.LogInfo(" (no Animator found anywhere in the hierarchy)");
Jotunn.Logger.LogInfo($"=== {prefabName} ATTACKS (from Humanoid.m_defaultItems) ===");
Humanoid humanoid = prefab.GetComponent<Humanoid>();
if (humanoid == null)
{
// Not every prefab worth checking is a creature - a registered weapon clone
// (e.g. `dumpelder SvermRavagerBite`) is an item on its own, and this is the only
// way to see what a runtime mutation (Attack.Clone() plus field edits) actually
// left on it, as opposed to what the SOURCE creature's own copy still says.
ItemDrop directItem = prefab.GetComponent<ItemDrop>();
if (directItem != null)
{
Jotunn.Logger.LogInfo(" (no Humanoid - dumping the prefab's own ItemDrop instead)");
DumpWeaponAttacks(prefab);
}
else
{
Jotunn.Logger.LogInfo(" (no Humanoid component and no ItemDrop on the prefab root)");
}
}
else
{
GameObject[] defaultItems = Traverse.Create(humanoid).Field<GameObject[]>("m_defaultItems").Value;
if (defaultItems == null || defaultItems.Length == 0)
{
Jotunn.Logger.LogInfo(" (m_defaultItems is empty)");
}
else
{
foreach (GameObject itemPrefab in defaultItems)
{
if (itemPrefab == null) continue;
DumpWeaponAttacks(itemPrefab);
}
}
ItemDrop unarmed = Traverse.Create(humanoid).Field<ItemDrop>("m_unarmedWeapon").Value;
if (unarmed != null) DumpWeaponAttacks(unarmed.gameObject);
}
Console.instance.Print($"Dumped '{prefabName}' to the BepInEx log.");
}
private static void DumpWeaponAttacks(GameObject itemPrefab)
{
ItemDrop drop = itemPrefab.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
Jotunn.Logger.LogInfo($" weapon '{itemPrefab.name}' ({shared.m_name}): damages={DumpDamageTypes(shared.m_damages)} " +
$"skill={shared.m_skillType}");
DumpAttack("primary", shared.m_attack);
DumpAttack("secondary", shared.m_secondaryAttack);
}
/// <summary>
/// Every field an "identical" replica would need: the hitbox shape (melee reach, angle,
/// height, offset, ray width), how the damage lands (multiplier, multi-hit, through
/// walls, force), the animation, and every VFX slot Attack.Start can fire - start, trail,
/// hit, hit-on-terrain, trigger, burst, plus anything it spawns on top of the swing.
/// </summary>
private static void DumpAttack(string label, Attack attack)
{
if (attack == null) return;
Jotunn.Logger.LogInfo(
$" {label}: animation='{attack.m_attackAnimation}' randomAnimations={attack.m_attackRandomAnimations} " +
$"chainLevels={attack.m_attackChainLevels} damageMultiplier={attack.m_damageMultiplier} " +
$"type={attack.m_attackType}");
Jotunn.Logger.LogInfo(
$" hitbox: range={attack.m_attackRange} angle={attack.m_attackAngle} " +
$"height={attack.m_attackHeight} offset={attack.m_attackOffset} rayWidth={attack.m_attackRayWidth} " +
$"originJoint='{attack.m_attackOriginJoint}' multiHit={attack.m_multiHit} " +
$"hitThroughWalls={attack.m_hitThroughWalls} hitFriendly={attack.m_hitFriendly} " +
$"hitTerrain={attack.m_hitTerrain} forceMultiplier={attack.m_forceMultiplier} " +
$"recoilPushback={attack.m_recoilPushback}");
Jotunn.Logger.LogInfo(
$" spawnOnTrigger='{(attack.m_spawnOnTrigger != null ? attack.m_spawnOnTrigger.name : "none")}' " +
$"spawnOnHit='{(attack.m_spawnOnHit != null ? attack.m_spawnOnHit.name : "none")}' " +
$"projectile='{(attack.m_attackProjectile != null ? attack.m_attackProjectile.name : "none")}'");
DumpEffectList("startEffect", attack.m_startEffect);
DumpEffectList("trailStartEffect", attack.m_trailStartEffect);
DumpEffectList("hitEffect", attack.m_hitEffect);
DumpEffectList("hitTerrainEffect", attack.m_hitTerrainEffect);
DumpEffectList("triggerEffect", attack.m_triggerEffect);
DumpEffectList("burstEffect", attack.m_burstEffect);
if (attack.m_attackProjectile != null)
{
Projectile proj = attack.m_attackProjectile.GetComponent<Projectile>();
if (proj == null) proj = attack.m_attackProjectile.GetComponentInChildren<Projectile>(true);
if (proj != null)
{
Jotunn.Logger.LogInfo($" projectile '{attack.m_attackProjectile.name}' damage={DumpDamageTypes(proj.m_damage)} aoe={proj.m_aoe}");
}
else
{
Jotunn.Logger.LogInfo($" projectile '{attack.m_attackProjectile.name}' has no Projectile component");
}
}
}
private static void DumpEffectList(string label, EffectList effects)
{
if (effects == null || effects.m_effectPrefabs == null || effects.m_effectPrefabs.Length == 0) return;
foreach (EffectList.EffectData data in effects.m_effectPrefabs)
{
if (data == null || data.m_prefab == null) continue;
Jotunn.Logger.LogInfo($" {label}: '{data.m_prefab.name}' attach={data.m_attach} " +
$"follow={data.m_follow} childTransform='{data.m_childTransform}'");
}
}
private static string DumpDamageTypes(HitData.DamageTypes d)
{
if (d == null) return "none";
return $"blunt={d.m_blunt} slash={d.m_slash} pierce={d.m_pierce} chop={d.m_chop} pickaxe={d.m_pickaxe} " +
$"fire={d.m_fire} frost={d.m_frost} lightning={d.m_lightning} poison={d.m_poison} spirit={d.m_spirit}";
}
private static void DumpTransform(Transform t, string indent)
{
if (t == null) return;
System.Text.StringBuilder components = new System.Text.StringBuilder();
foreach (Component c in t.GetComponents<Component>())
{
if (c != null) components.Append(c.GetType().Name).Append(" ");
}
Jotunn.Logger.LogInfo($"{indent}{t.name} [{components}]");
for (int i = 0; i < t.childCount; i++) DumpTransform(t.GetChild(i), indent + " ");
}
private static string GetPath(Transform t)
{
string path = t.name;
while (t.parent != null)
{
t = t.parent;
path = t.name + "/" + path;
}
return path;
}
}
public class ResetProgressionCommand : ConsoleCommand
{
public override string Name => "resetprogression";
public override string Help => "[DEBUG] Resets the progression state to natural world state";
public override void Run(string[] args)
{
RacesOfValheim.ResetProgression(out string summary);
Console.instance.Print($"[DEBUG] {summary}");
}
}
/// <summary>
/// Ground truth for "does this prefab actually exist", the same problem that made
/// SummonOnKill's rise VFX ("vfx_skeleton_spawn", "vfx_bloodmagic_aoe") a guess instead of a
/// fact. ZNetScene.GetPrefabNames() is the live registry the running game actually built, so
/// this beats grepping asset bundles offline - those are compressed and unsearchable as plain
/// text, which is exactly why that VFX name had to be confirmed in-game instead.
/// </summary>
public class ListPrefabsCommand : ConsoleCommand
{
public override string Name => "listprefabs";
public override string Help => "[DEBUG] Logs every ZNetScene prefab name containing the given substring (case-insensitive)";
public override void Run(string[] args)
{
if (args.Length == 0)
{
Console.instance.Print("Usage: listprefabs <substring>");
return;
}
if (ZNetScene.instance == null)
{
Console.instance.Print("ZNetScene is not ready yet.");
return;
}
string filter = args[0];
System.Collections.Generic.List<string> matches = new System.Collections.Generic.List<string>();
foreach (string prefabName in ZNetScene.instance.GetPrefabNames())
{
if (prefabName.IndexOf(filter, System.StringComparison.OrdinalIgnoreCase) >= 0)
{
matches.Add(prefabName);
}
}
matches.Sort();
Console.instance.Print($"[DEBUG] {matches.Count} prefab(s) containing '{filter}':");
Jotunn.Logger.LogInfo($"[DEBUG] listprefabs '{filter}': {matches.Count} match(es)");
foreach (string name in matches)
{
Console.instance.Print(" " + name);
Jotunn.Logger.LogInfo(" " + name);
}
}
}
}