RacesOfValheim/JotunnModStub/Aswid/AswidPatches.cs
kanym 5c41d80cae feat(aswid): running water weakness and a seasick camera
Swimming costs double stamina, scaled on vanilla's own swim charge so
its drowning check does the rest at high settings. Over deep water in
the Ocean, swimming or flying, the Aswid loses health and stamina each
second; a boat protects. A gentle camera roll plays while the sea hurts,
kept local through ConfigSync so a server cannot force it on anyone.
2026-10-26 15:26:25 +01:00

953 lines
42 KiB
C#

using HarmonyLib;
using UnityEngine;
using System.Linq;
namespace RacesOfValheim
{
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class AswidSkinColorPatch
{
private static readonly Color SkinColor = new Color(0.96f, 0.97f, 0.98f, 1f);
private static readonly Color HairColor = new Color(1f, 1f, 1f, 1f);
public static void Postfix(VisEquipment __instance)
{
if (!__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null) return;
string race = "Human";
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
race = nview.GetZDO().GetString("RacesOfValheim_Race", "Human");
else if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string savedRace))
race = savedRace;
// Before the race check, because it takes the eyes off anyone who has stopped being
// an Aswid as well as putting them on anyone who is one.
AswidVisuals.ApplyEyes(player);
if (race != "Aswid") return;
int state = 0;
if (nview != null && nview.IsValid())
state = nview.GetZDO().GetInt("RacesOfValheim_AswidState", 0);
Color currentHairColor = state >= 8 ? new Color(0.02f, 0.02f, 0.02f, 1f) : HairColor;
if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null)
__instance.m_bodyModel.material.SetColor("_SkinColor", SkinColor);
var hairInst = Traverse.Create(__instance).Field("m_hairItemInstance").GetValue<GameObject>();
if (hairInst != null)
foreach (var r in hairInst.GetComponentsInChildren<Renderer>())
if (r.material != null) r.material.SetColor("_SkinColor", currentHairColor);
var beardInst = Traverse.Create(__instance).Field("m_beardItemInstance").GetValue<GameObject>();
if (beardInst != null)
foreach (var r in beardInst.GetComponentsInChildren<Renderer>())
if (r.material != null) r.material.SetColor("_SkinColor", currentHairColor);
}
}
// Valheim 1.0 appended a 'short variant' parameter to this overload. The type array has to
// match it exactly or the patch silently fails to bind and PatchAll throws.
[HarmonyPatch(typeof(SEMan), "AddStatusEffect", new System.Type[] { typeof(int), typeof(bool), typeof(int), typeof(float), typeof(short) })]
public static class AswidSEManPatch
{
public static bool Prefix(SEMan __instance, ref int nameHash)
{
Character character = Traverse.Create(__instance).Field<Character>("m_character").Value;
if (character == Player.m_localPlayer && AswidRace.IsAswid())
{
int state = BossProgressionManager.GetCurrentProgressionState();
if (state >= 5 && nameHash == "Freezing".GetStableHashCode())
{
return false;
}
// Cold immunity is removed as per user request to test native Cold VFX
// if (nameHash == "Cold".GetStableHashCode())
// {
// return false;
// }
}
return true;
}
}
[HarmonyPatch(typeof(Attack), "Start")]
public static class Aswid_BloodMagicCost_Patch
{
private static float savedHealthCost = 0f;
private static float savedHealthPercentage = 0f;
public static void Prefix(Attack __instance, Humanoid character, ref bool __state)
{
var weapon = Traverse.Create(__instance).Field("m_weapon").GetValue<ItemDrop.ItemData>();
if (weapon == null) weapon = Traverse.Create(__instance).Method("GetWeapon").GetValue<ItemDrop.ItemData>();
if (character == Player.m_localPlayer && AswidRace.IsAswid() && weapon != null && weapon.m_shared.m_skillType == Skills.SkillType.BloodMagic)
{
__state = true;
savedHealthCost = weapon.m_shared.m_attack.m_attackHealth;
savedHealthPercentage = weapon.m_shared.m_attack.m_attackHealthPercentage;
weapon.m_shared.m_attack.m_attackHealth = 0f;
weapon.m_shared.m_attack.m_attackHealthPercentage = 0f;
}
else
{
__state = false;
}
}
public static void Postfix(Attack __instance, Humanoid character, bool __state)
{
var weapon = Traverse.Create(__instance).Field("m_weapon").GetValue<ItemDrop.ItemData>();
if (weapon == null) weapon = Traverse.Create(__instance).Method("GetWeapon").GetValue<ItemDrop.ItemData>();
if (__state && weapon != null)
{
weapon.m_shared.m_attack.m_attackHealth = savedHealthCost;
weapon.m_shared.m_attack.m_attackHealthPercentage = savedHealthPercentage;
}
}
}
public static class AswidPatches
{
public static System.Collections.Generic.Dictionary<ZDOID, float> RecentlyLifeDrained = new System.Collections.Generic.Dictionary<ZDOID, float>();
}
[HarmonyPatch(typeof(Character), "Damage")]
public static class Aswid_LifeDrainKill_Patch
{
public static void Postfix(Character __instance, HitData hit)
{
if (hit != null && hit.m_attacker == Player.m_localPlayer?.GetZDOID())
{
Debug.LogWarning($"[Aswid_Patch] Local player damaged {__instance.name}. IsDead: {__instance.IsDead()}");
}
if (__instance.IsDead() && hit != null)
{
if (Player.m_localPlayer != null && hit.m_attacker == Player.m_localPlayer.GetZDOID())
{
ZNetView cNetView = __instance.GetComponent<ZNetView>();
if (AswidRace.IsAswid() && cNetView != null && cNetView.IsValid())
{
ZDOID zdoid = __instance.GetZDOID();
if (AswidPatches.RecentlyLifeDrained.TryGetValue(zdoid, out float timeHit))
{
if (Time.time - timeHit < 1.0f)
{
Debug.LogWarning($"[Aswid] {__instance.name} died within 1s of LifeDrain. Consuming!");
AswidRace.TryConsumeMob(__instance, __instance.GetMaxHealth());
AswidPatches.RecentlyLifeDrained.Remove(zdoid);
}
}
}
}
}
}
}
[HarmonyPatch(typeof(Character), "Awake")]
public static class Aswid_Awake_Patch
{
public static void Postfix(Character __instance)
{
if (__instance.GetComponent<MonsterAI>() != null && !__instance.IsBoss() && __instance.m_faction != Character.Faction.Demon && __instance.GetComponent<Tameable>() == null)
{
if (__instance.GetComponent<AswidThrall>() == null)
{
__instance.gameObject.AddComponent<AswidThrall>();
}
}
}
}
[HarmonyPatch(typeof(Player), "GetBodyArmor")]
public static class Aswid_ArmorBonus_Patch
{
public static void Postfix(Player __instance, ref float __result)
{
if (__instance == Player.m_localPlayer && AswidRace.IsAswid())
{
int state = BossProgressionManager.GetCurrentProgressionState();
float multiplier = (EnvMan.instance != null && EnvMan.IsNight()) ? AswidConfig.NightMultiplier.Value : 1f;
__result += AswidConfig.ArmorBonusPerState.Value * state * multiplier;
}
}
}
[HarmonyPatch]
public static class Aswid_DamageBonus_Patch
{
[HarmonyTargetMethod]
public static System.Reflection.MethodBase TargetMethod()
{
return System.Linq.Enumerable.FirstOrDefault(
HarmonyLib.AccessTools.GetDeclaredMethods(typeof(ItemDrop.ItemData)),
m => m.Name == "GetDamage" && m.ReturnType == typeof(HitData.DamageTypes)
);
}
public static void Postfix(ItemDrop.ItemData __instance, ref HitData.DamageTypes __result)
{
if (Player.m_localPlayer != null && AswidRace.IsAswid() &&
Player.m_localPlayer.GetInventory().ContainsItem(__instance))
{
int state = BossProgressionManager.GetCurrentProgressionState();
if (state > 0)
{
float multiplier = (EnvMan.instance != null && EnvMan.IsNight()) ? AswidConfig.NightMultiplier.Value : 1f;
float bonus = AswidConfig.DamageBonusPerState.Value * state * multiplier;
// Add flat bonus to physical damage types that the weapon already has
if (__result.m_slash > 0) __result.m_slash += bonus;
if (__result.m_blunt > 0) __result.m_blunt += bonus;
if (__result.m_pierce > 0) __result.m_pierce += bonus;
if (__result.m_chop > 0) __result.m_chop += bonus;
if (__result.m_pickaxe > 0) __result.m_pickaxe += bonus;
}
}
}
}
/// <summary>
/// Fire and pierce hurt the Aswid more: fire for the old way vampires end, pierce for the
/// stake. A plain multiplier, like the Trol's fire weakness, rather than DamageModifier.Weak,
/// which is a fixed +50% with nothing in between. ApplyDamage runs after resistances, so a
/// fire resistance mead still helps, and Mist Form's pierce immunity has already zeroed the
/// pierce by the time this sees it.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage")]
public static class Aswid_Weakness_Patch
{
public static void Prefix(Character __instance, ref HitData hit)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return;
if (AswidRace.HasFireWeakness(BossProgressionManager.GetCurrentProgressionState()) && hit.m_damage.m_fire > 0f)
{
hit.m_damage.m_fire *= 1f + AswidConfig.FireWeakness.Value;
}
if (AswidConfig.PierceWeaknessEnabled.Value && hit.m_damage.m_pierce > 0f)
{
hit.m_damage.m_pierce *= 1f + AswidConfig.PierceWeakness.Value;
}
}
}
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Aswid_Attack_Patch
{
public static bool Prefix(Humanoid __instance)
{
if (__instance == Player.m_localPlayer)
{
if (__instance.GetComponentInChildren<BatFormBehavior>() != null)
{
return false;
}
if (__instance.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()))
{
return false;
}
}
return true;
}
}
/// <summary>
/// Bat and mist form shut the rest of the human's attack loop as well as StartAttack: crossbow
/// reload and draw live in PlayerAttackInput, and the form's Animator fires the held attack
/// through OnAttackTrigger. See Fenrir's BlockPlayerAttackInputPatch.
/// </summary>
public static class AswidFormAttackLoop
{
public static bool InForm(Humanoid player)
{
if (player != Player.m_localPlayer) return false;
return player.GetComponentInChildren<BatFormBehavior>() != null
|| player.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode());
}
}
[HarmonyPatch(typeof(Player), "PlayerAttackInput")]
public static class Aswid_BlockAttackInput_Patch
{
public static bool Prefix(Player __instance) => !AswidFormAttackLoop.InForm(__instance);
}
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))]
public static class Aswid_BlockAttackTrigger_Patch
{
public static bool Prefix(Humanoid __instance) => !AswidFormAttackLoop.InForm(__instance);
}
[HarmonyPatch(typeof(Character), "SetRun")]
public static class Aswid_Run_Patch
{
public static void Prefix(Character __instance, ref bool run)
{
if (__instance == Player.m_localPlayer)
{
if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()))
{
run = false;
}
}
}
}
[HarmonyPatch(typeof(Character), "Jump")]
public static class Aswid_Jump_Patch
{
public static bool Prefix(Character __instance)
{
if (__instance == Player.m_localPlayer)
{
if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()))
{
return false;
}
}
return true;
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class Aswid_PlayerOnSpawned_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == Player.m_localPlayer)
{
AswidFoodManager.LoadFood(__instance);
}
}
}
[HarmonyPatch(typeof(Player), "CanConsumeItem")]
public static class Aswid_CanConsumeItem_Patch
{
public static void Postfix(Player __instance, ItemDrop.ItemData item, ref bool __result)
{
if (__instance == Player.m_localPlayer && AswidRace.IsAswid() && AswidBloodRefinery.IsAswidMeal(item))
{
var foods = HarmonyLib.Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.IList>();
if (foods != null)
{
if (foods.Count >= 3)
{
bool canUse4th = BossProgressionManager.GetCurrentProgressionState() >= 8;
bool has4th = AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null;
if (canUse4th && (!has4th || extraFood.m_time >= (extraFood.m_item.m_shared.m_foodBurnTime * 0.5f)))
{
__result = true; // Consente l'uso del 4° slot se disponibile
}
else
{
bool canRefresh = false;
foreach (object foodObj in foods)
{
Player.Food f = foodObj as Player.Food;
if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain())
{
canRefresh = true;
break;
}
}
// Otherwise vanilla's answer stands: it already allows replacing the
// most depleted meal past half its time, and already showed its "too
// full" message when it refused. Forcing false here used to block
// that replacement, silently.
if (canRefresh) __result = true;
}
}
else
{
__result = true; // Spazio nei primi 3 slot
}
}
}
}
}
[HarmonyPatch(typeof(Player), "EatFood")]
public static class Aswid_EatFood_Patch
{
private static System.Collections.Generic.List<object> hiddenFoods = new System.Collections.Generic.List<object>();
public static bool Prefix(Player __instance, ItemDrop.ItemData item, ref bool __result)
{
hiddenFoods.Clear();
if (__instance == Player.m_localPlayer && AswidRace.IsAswid() && AswidBloodRefinery.IsAswidMeal(item))
{
var m_foods = HarmonyLib.Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.IList>();
if (m_foods != null)
{
if (m_foods.Count >= 3)
{
bool canUse4th = BossProgressionManager.GetCurrentProgressionState() >= 8;
if (canUse4th)
{
bool has4th = AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null;
if (!has4th || extraFood.m_time >= (extraFood.m_item.m_shared.m_foodBurnTime * 0.5f))
{
AswidFoodManager.SetExtraFood(__instance, item);
// Play consume effects
var consumeEffects = HarmonyLib.Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue<EffectList>();
if (consumeEffects != null)
{
consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1);
}
var zanim = HarmonyLib.Traverse.Create(__instance).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null)
{
zanim.SetTrigger("eat");
}
if (item.m_shared.m_food > 0f)
{
__instance.Heal(item.m_shared.m_food, true);
}
__result = true;
return false; // Skip native EatFood
}
}
bool refreshed = false;
foreach (object foodObj in m_foods)
{
Player.Food f = foodObj as Player.Food;
if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain())
{
// Was `f.m_time = 0f`, which expired the meal instead of renewing
// it - see RaceFoodRefresh for the whole story. The fourth slot
// above genuinely does count up from zero; this list does not.
RaceFoodRefresh.Refresh(__instance, f, item);
refreshed = true;
break;
}
}
if (refreshed)
{
__result = true;
return false;
}
// Full, no fourth slot free, no slot holding this meal. Native EatFood
// replaces the most depleted meal past half its time, or refuses.
return true;
}
else
{
// Nascondiamo temporaneamente i duplicati nei primi 3 slot per costringere Valheim ad aggiungere un NUOVO slot
for (int i = m_foods.Count - 1; i >= 0; i--)
{
var foodObj = m_foods[i];
var foodItem = HarmonyLib.Traverse.Create(foodObj).Field("m_item").GetValue<ItemDrop.ItemData>();
if (foodItem != null && foodItem.m_shared.m_name == item.m_shared.m_name)
{
hiddenFoods.Add(foodObj);
m_foods.RemoveAt(i);
}
}
}
}
}
return true;
}
public static void Postfix(Player __instance, ItemDrop.ItemData item, ref bool __result)
{
if (hiddenFoods.Count > 0)
{
var m_foods = HarmonyLib.Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.IList>();
if (m_foods != null)
{
// Ripristiniamo i duplicati nascosti
foreach (var hf in hiddenFoods)
{
m_foods.Add(hf);
}
}
hiddenFoods.Clear();
}
}
}
[HarmonyPatch(typeof(Tameable), "GetHoverText")]
public static class Aswid_TameHoverText_Patch
{
public static void Postfix(Tameable __instance, ref string __result)
{
if (Player.m_localPlayer == null || !AswidRace.IsAswid()) return;
if (__instance.GetComponent<Character>()?.IsTamed() == true) return;
string prefabName = __instance.gameObject.name.ToLower();
int state = BossProgressionManager.GetCurrentProgressionState();
bool canTame = false;
if (state >= 2 && prefabName.Contains("boar")) canTame = true;
if (state >= 5 && prefabName.Contains("wolf")) canTame = true;
if (state >= 6 && prefabName.Contains("lox")) canTame = true;
if (state >= 8 && prefabName.Contains("asksvin")) canTame = true;
if (canTame)
{
// Used to hardcode "[K] Tame" while AswidRace.Update actually checked U (now
// AswidConfig.TameKey) - the hint never matched the working key, and would have
// gone stale again the moment that key was rebound. MainKey.ToString() reads back
// whatever is actually bound.
__result += ModText.Get("rov_hover_aswid_tame", AswidConfig.TameKey.Value.MainKey);
}
}
}
[HarmonyPatch(typeof(Hud), "UpdateStamina")]
public static class Aswid_HideStamina_Patch
{
public static bool Prefix(Hud __instance, Player player)
{
if (player == Player.m_localPlayer && DraughRace.IsDraugh())
{
if (__instance.m_staminaBar2Root != null && __instance.m_staminaBar2Root.gameObject.activeSelf)
{
__instance.m_staminaBar2Root.gameObject.SetActive(false);
}
return false;
}
// Vanilla switches the bar on once, when the HUD is built, and never again. Without
// this a player who left the Draugh had no stamina bar until relog - and an Aswid
// updating from a version that still hid it would have none either.
if (player == Player.m_localPlayer && __instance.m_staminaBar2Root != null
&& !__instance.m_staminaBar2Root.gameObject.activeSelf)
{
__instance.m_staminaBar2Root.gameObject.SetActive(true);
}
return true;
}
}
[HarmonyPatch(typeof(StatusEffect), "Setup")]
public static class Aswid_ColdStatus_Patch
{
public static void Prefix(StatusEffect __instance, Character character)
{
if (character == Player.m_localPlayer && AswidRace.IsAswid() && (__instance.name.Contains("Cold") || __instance.m_name == "$se_cold_name"))
{
var wraithTrophy = Jotunn.Managers.PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyWraith");
if (wraithTrophy != null && wraithTrophy.m_itemData.m_shared.m_icons.Length > 0)
{
__instance.m_icon = wraithTrophy.m_itemData.m_shared.m_icons[0];
}
else
{
__instance.m_icon = null;
}
__instance.m_name = "$rov_se_aswid_nightaura_name";
__instance.m_startMessage = ""; // "The darkness empowers you.";
__instance.m_tooltip = "$rov_se_aswid_nightaura_tooltip";
if (__instance is SE_Stats stats)
{
stats.m_healthRegenMultiplier = 1f;
stats.m_staminaRegenMultiplier = 1f;
stats.m_staminaDrainPerSec = 0f;
stats.m_speedModifier = 0f;
}
}
}
}
[HarmonyPatch(typeof(Player), "Update")]
public static class Aswid_PlayerUpdate_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == null) return;
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.ToggleDevourKey.Value.IsDownIgnoringHeldKeys())
{
AswidRace.DevourEnabled = !AswidRace.DevourEnabled;
AswidRace.AuraEnabled = AswidRace.DevourEnabled;
string msg = ModText.Get(AswidRace.DevourEnabled ? "rov_msg_aswid_aura_enabled" : "rov_msg_aswid_aura_disabled");
__instance.Message(MessageHud.MessageType.Center, msg);
}
int state = BossProgressionManager.GetCurrentProgressionState();
var rules = AswidProgression.GetRules(state);
if (AswidRace.Instance != null && !AswidRace.Instance.IsTransformed)
{
if (rules != null && rules.HasSurtlingForm)
{
__instance.transform.localScale = new Vector3(1.1f, 1.1f, 1.1f);
}
else
{
__instance.transform.localScale = Vector3.one;
}
}
}
}
}
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
public static class Aswid_MultiplayerVisuals_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (!__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null || player.IsOwner()) return; // Only process for remote players
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Aswid")
{
bool isBat = nview.GetZDO().GetBool("Aswid_IsBatForm", false);
bool isMist = nview.GetZDO().GetBool("Aswid_IsMistForm", false);
// The bat flies on m_flying, which only the bat's own client sets. Mirror it here
// and switch gravity off for the duration, or this copy sinks to the terrain
// whatever altitude is replicated - the same fix ZdoVisualSync applies to drakes.
HarmonyLib.Traverse.Create(player).Field("m_flying").SetValue(isBat);
Rigidbody body = player.GetComponent<Rigidbody>();
if (body != null && body.useGravity == isBat) body.useGravity = !isBat;
Transform playerVisual = player.transform.Find("Visual");
// Bat logic
Transform batBody = player.transform.Find("AswidBody_Bat");
if (isBat && batBody == null) {
GameObject batPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("Bat");
if (batPrefab != null) {
GameObject visualPrefab = batPrefab.GetComponentInChildren<Animator>()?.gameObject;
if (visualPrefab != null) {
GameObject batInstance = UnityEngine.Object.Instantiate(visualPrefab, player.transform.position, player.transform.rotation, player.transform);
batInstance.name = "AswidBody_Bat";
batInstance.transform.localPosition = Vector3.zero;
}
}
} else if (!isBat && batBody != null) {
UnityEngine.Object.Destroy(batBody.gameObject);
}
// Mist logic
Transform mistBody = player.transform.Find("AswidBody_Mist");
if (isMist && mistBody == null) {
GameObject wraithPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("Wraith");
if (wraithPrefab != null) {
GameObject visualPrefab = wraithPrefab.transform.Find("Visual")?.gameObject;
if (visualPrefab != null) {
GameObject mistInstance = UnityEngine.Object.Instantiate(visualPrefab, player.transform.position, player.transform.rotation, player.transform);
mistInstance.name = "AswidBody_Mist";
mistInstance.transform.localPosition = Vector3.zero;
mistInstance.transform.localScale = Vector3.one;
foreach (var r in mistInstance.GetComponentsInChildren<Renderer>())
{
if (r.material != null && r.material.HasProperty("_Color"))
{
Color c = r.material.GetColor("_Color");
c.a = 0.3f; // Make transparent
r.material.SetColor("_Color", c);
}
}
}
}
} else if (!isMist && mistBody != null) {
UnityEngine.Object.Destroy(mistBody.gameObject);
}
// Toggle visibility
if (isBat || isMist) {
PlayerVisualHider.Hide(playerVisual, "aswid-remote-form");
} else {
PlayerVisualHider.Show(playerVisual, "aswid-remote-revert");
}
}
}
}
[HarmonyPatch(typeof(Character), "Damage")]
public static class Aswid_Damage_Patch
{
public static void Prefix(Character __instance, HitData hit, out float __state)
{
__state = (__instance != null) ? __instance.GetHealth() : 0f;
}
public static void Postfix(Character __instance, HitData hit, float __state)
{
if (hit == null || __instance == null || __instance.IsPlayer()) return;
Character attacker = hit.GetAttacker();
if (attacker != null && attacker.IsPlayer() && attacker == Player.m_localPlayer)
{
ZNetView nview = attacker.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Aswid")
{
float physDamage = hit.m_damage.m_blunt + hit.m_damage.m_slash + hit.m_damage.m_pierce + hit.m_damage.m_chop + hit.m_damage.m_pickaxe + hit.m_damage.m_damage;
// On-hit Lifesteal
if (physDamage > 0f)
{
int currentState = BossProgressionManager.GetCurrentProgressionState();
var rules = AswidProgression.GetRules(currentState);
float lifesteal = rules.LifestealPercent;
if (EnvMan.instance != null && EnvMan.IsNight())
{
lifesteal *= AswidConfig.NightMultiplier.Value;
}
if (lifesteal > 0f)
{
float healAmount = physDamage * lifesteal;
Player.m_localPlayer.Heal(healAmount, true);
}
}
// On-death Devour
if (__state > 0f && __instance.GetHealth() <= 0f && physDamage > 0f)
{
AswidRace.TryConsumeMob(__instance, __instance.GetMaxHealth());
}
}
}
}
/// <summary>
/// True while the local Aswid is holding a blood magic item. The three eitr patches below
/// all turn on exactly this condition, so it lives in one place rather than three.
/// </summary>
public static bool IsLocalAswidWieldingBloodMagic(Character character)
{
if (character == null || character != Player.m_localPlayer) return false;
if (!AswidRace.IsAswid()) return false;
ItemDrop.ItemData weapon = Player.m_localPlayer.GetCurrentWeapon();
return weapon != null && weapon.m_shared != null &&
weapon.m_shared.m_skillType == Skills.SkillType.BloodMagic;
}
/// <summary>
/// The gate that actually decides whether a blood magic attack may start, and the reason
/// Blood Magic Mastery did nothing.
///
/// Attack.Start asks Character.TryUseEitr, whose very first test is:
///
/// if (GetMaxEitr() == 0) { Message("$hud_eitrrequired"); return false; }
///
/// An Aswid carrying no eitr food has a maximum of zero, so the attack was refused right
/// there - before HaveEitr was ever consulted, which is why forcing HaveEitr true (below)
/// changed nothing on its own. Freeing the cast has to happen here.
///
/// TryUseEitr only ever gates; the spend happens separately through UseEitr, so returning
/// true costs nothing. The health price of blood magic is charged elsewhere and is left
/// completely alone - it is meant to be the whole price.
/// </summary>
[HarmonyPatch(typeof(Character), "TryUseEitr")]
public static class Character_TryUseEitr_Patch
{
public static bool Prefix(Character __instance, ref bool __result)
{
if (!IsLocalAswidWieldingBloodMagic(__instance)) return true;
__result = true;
return false;
}
}
[HarmonyPatch(typeof(Player), "HaveEitr")]
public static class Player_HaveEitr_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
// Still needed for the paths that ask HaveEitr directly rather than through
// TryUseEitr - Attack.FireProjectileBurst and the bow/crossbow draw among them.
if (IsLocalAswidWieldingBloodMagic(__instance)) __result = true;
}
}
[HarmonyPatch(typeof(Player), "UseEitr")]
public static class Player_UseEitr_Patch
{
public static bool Prefix(Player __instance)
{
if (IsLocalAswidWieldingBloodMagic(__instance)) return false; // Skip spending Eitr
return true;
}
}
[HarmonyPatch(typeof(Skills), "RaiseSkill")]
public static class Aswid_Skills_RaiseSkill_Patch
{
public static void Prefix(Skills __instance, Skills.SkillType skillType, ref float factor)
{
Player player = HarmonyLib.Traverse.Create(__instance).Field("m_player").GetValue<Player>();
if (player != null && player == Player.m_localPlayer && AswidRace.IsAswid())
{
if (skillType == Skills.SkillType.BloodMagic)
{
factor *= AswidConfig.BloodMagicSkillGainMultiplier.Value; // Benedictus et Afflictus
}
}
}
}
}
[HarmonyPatch(typeof(Player), "UpdateFood")]
public static class Aswid_PlayerUpdateFood_Patch
{
public static void Prefix(Player __instance, float dt, bool forceUpdate)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return;
if (AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null)
{
extraFood.m_time += dt;
if (extraFood.m_item != null && extraFood.m_item.m_shared != null)
{
if (extraFood.m_time >= extraFood.m_item.m_shared.m_foodBurnTime)
{
AswidFoodManager.ClearFood(__instance);
}
else
{
float factor = extraFood.m_time / extraFood.m_item.m_shared.m_foodBurnTime;
extraFood.m_health = Mathf.Lerp(extraFood.m_item.m_shared.m_food, extraFood.m_item.m_shared.m_food * 0.2f, factor);
extraFood.m_stamina = Mathf.Lerp(extraFood.m_item.m_shared.m_foodStamina, extraFood.m_item.m_shared.m_foodStamina * 0.2f, factor);
extraFood.m_eitr = Mathf.Lerp(extraFood.m_item.m_shared.m_foodEitr, extraFood.m_item.m_shared.m_foodEitr * 0.2f, factor);
}
}
}
}
}
[HarmonyPatch(typeof(Player), "GetTotalFoodValue")]
public static class Aswid_PlayerGetTotalFoodValue_Patch
{
public static void Postfix(Player __instance, ref float hp, ref float stamina, ref float eitr)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return;
if (AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null)
{
hp += extraFood.m_health;
stamina += extraFood.m_stamina;
eitr += extraFood.m_eitr;
}
// Added on top of whatever vanilla and other mods put here, never assigned: a mod that
// raises max stamina has to keep raising it for an Aswid too.
stamina += AswidRace.GetStaminaBonus(BossProgressionManager.GetCurrentProgressionState());
}
}
/// <summary>
/// The Aswid's stamina. It used to be infinite: the Skeleton's UseStamina skip covered the
/// Aswid too, which made every stamina mod, food and skill meaningless for the race (the Discord
/// reports that started the rebalance). The cost is now scaled rather than skipped, so the
/// call still reaches vanilla - and any other mod patching it - with a smaller number.
/// </summary>
[HarmonyPatch(typeof(Player), "UseStamina")]
public static class Aswid_UseStamina_Patch
{
public static void Prefix(Player __instance, ref float v)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return;
v *= AswidConfig.StaminaCostMultiplier.Value;
if (Aswid_SwimCost_Patch.Swimming && AswidConfig.RunningWaterEnabled.Value)
{
v *= AswidConfig.SwimStaminaMultiplier.Value;
}
}
}
/// <summary>
/// Marks the frames where vanilla charges for a swim stroke, so Aswid_UseStamina_Patch can
/// make that one cost dearer. Player.OnSwimming is the only place swimming spends stamina,
/// and it also runs the drowning check right after - which is what makes a high multiplier
/// play as "cannot swim" without any code of ours deciding who drowns.
/// </summary>
[HarmonyPatch(typeof(Player), "OnSwimming")]
public static class Aswid_SwimCost_Patch
{
public static bool Swimming { get; private set; }
public static void Prefix(Player __instance)
{
Swimming = __instance == Player.m_localPlayer;
}
public static void Finalizer()
{
Swimming = false;
}
}
/// <summary>
/// The seasick camera: a slow roll while the open sea is hurting the Aswid. Applied after
/// vanilla has settled the camera's rotation for the frame, as a roll around the view axis,
/// so it never moves where the player aims - only how the horizon sits.
/// </summary>
[HarmonyPatch(typeof(GameCamera), "GetCameraPosition")]
public static class Aswid_SeaCameraSway_Patch
{
private const float DegreesAtStrengthOne = 4f;
private static float sway;
public static void Postfix(float dt, ref Quaternion rot)
{
bool on = AswidRace.AtSea && AswidConfig.SeaCameraSway.Value && AswidRace.IsAswid() &&
Player.m_localPlayer != null && !Player.m_localPlayer.IsDead();
// Eased in and out over about a second, so leaving the sea does not snap the horizon.
sway = Mathf.MoveTowards(sway, on ? 1f : 0f, dt);
if (sway <= 0f) return;
float t = Time.time;
float roll = (Mathf.Sin(t * 0.9f) + 0.4f * Mathf.Sin(t * 2.3f)) * DegreesAtStrengthOne *
AswidConfig.SeaCameraSwayStrength.Value * sway;
rot *= Quaternion.AngleAxis(roll, Vector3.forward);
}
}
[HarmonyPatch(typeof(Player), "ClearFood")]
public static class Aswid_Player_ClearFood_Patch
{
public static bool Prefix(Player __instance)
{
if (__instance == Player.m_localPlayer && AswidRace.IsAswid())
{
// Retain food if the player is dead/dying.
// Allows Bukeperries to still clear food normally.
if (__instance.IsDead() || __instance.GetHealth() <= 0f)
{
Jotunn.Logger.LogInfo("[AswidRace] Preserving food buffs through death (Aswid racial trait).");
return false;
}
}
return true;
}
}
}