Merge branch 'fix-skadi-race'

This commit is contained in:
kanym 2026-08-01 13:50:25 +02:00
commit 51a23202ff
14 changed files with 397 additions and 87 deletions

View file

@ -521,7 +521,7 @@ namespace RacesOfValheim
ZNetView nview = __instance.GetComponent<ZNetView>(); ZNetView nview = __instance.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Aswid") if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Aswid")
{ {
if (__instance == Player.m_localPlayer && Input.GetKeyDown(KeyCode.I)) if (__instance == Player.m_localPlayer && RaceInput.Allowed && Input.GetKeyDown(KeyCode.I))
{ {
AswidRace.DevourEnabled = !AswidRace.DevourEnabled; AswidRace.DevourEnabled = !AswidRace.DevourEnabled;
string msg = AswidRace.DevourEnabled ? "Devour Ability: ENABLED" : "Devour Ability: DISABLED"; string msg = AswidRace.DevourEnabled ? "Devour Ability: ENABLED" : "Devour Ability: DISABLED";

View file

@ -504,8 +504,7 @@ namespace RacesOfValheim
int state = BossProgressionManager.GetCurrentProgressionState(); int state = BossProgressionManager.GetCurrentProgressionState();
bool takeInput = HarmonyLib.Traverse.Create(Player.m_localPlayer).Method("TakeInput").GetValue<bool>(); if (RaceInput.Allowed)
if (takeInput)
{ {
if (Input.GetKeyDown(KeyCode.G)) { TryTransformWithRules(AswidProgression.GetGKeyRules(state)); return; } if (Input.GetKeyDown(KeyCode.G)) { TryTransformWithRules(AswidProgression.GetGKeyRules(state)); return; }
if (Input.GetKeyDown(KeyCode.H)) { TryToggleMistForm(); return; } if (Input.GetKeyDown(KeyCode.H)) { TryToggleMistForm(); return; }

View file

@ -56,7 +56,7 @@ namespace RacesOfValheim
fenrirAnim.SetFloat("sideway_speed", playerAnim.GetFloat("sideway_speed")); fenrirAnim.SetFloat("sideway_speed", playerAnim.GetFloat("sideway_speed"));
} }
} }
if (isGrounded) if (isGrounded && RaceInput.Allowed)
{ {
if (Input.GetKeyDown(KeyCode.O)) if (Input.GetKeyDown(KeyCode.O))
{ {
@ -311,8 +311,12 @@ namespace RacesOfValheim
if (isGrounded) if (isGrounded)
{ {
// Gated per-read rather than around the block, so opening a GUI mid-stream
// still falls through to StopFire() instead of leaving the flames running.
bool canAct = RaceInput.Allowed;
// Fire attack on Right Click // Fire attack on Right Click
if (Input.GetMouseButton(1)) if (canAct && Input.GetMouseButton(1))
{ {
if (Player.m_localPlayer.GetEitr() > 0) if (Player.m_localPlayer.GetEitr() > 0)
{ {
@ -335,18 +339,18 @@ namespace RacesOfValheim
StopFire(); StopFire();
} }
if (Input.GetKeyDown(KeyCode.O)) if (canAct && Input.GetKeyDown(KeyCode.O))
{ {
StartCoroutine(HowlRoutine()); StartCoroutine(HowlRoutine());
} }
// Attacks on Left Click // Attacks on Left Click
if (Input.GetMouseButtonDown(0) && !isShootingFire) if (canAct && Input.GetMouseButtonDown(0) && !isShootingFire)
{ {
StartCoroutine(ClawRoutine()); // Single claw StartCoroutine(ClawRoutine()); // Single claw
} }
// Double claw on Middle Click // Double claw on Middle Click
else if (Input.GetMouseButtonDown(2) && !isShootingFire) else if (canAct && Input.GetMouseButtonDown(2) && !isShootingFire)
{ {
StartCoroutine(DoubleClawRoutine()); StartCoroutine(DoubleClawRoutine());
} }
@ -671,7 +675,7 @@ namespace RacesOfValheim
} }
} }
if (isGrounded) if (isGrounded && RaceInput.Allowed)
{ {
if (Input.GetMouseButtonDown(0)) // Left Click if (Input.GetMouseButtonDown(0)) // Left Click
{ {
@ -844,7 +848,7 @@ namespace RacesOfValheim
} }
} }
if (isGrounded) if (isGrounded && RaceInput.Allowed)
{ {
if (Input.GetMouseButtonDown(0)) // Left Click if (Input.GetMouseButtonDown(0)) // Left Click
{ {

View file

@ -143,6 +143,8 @@ namespace RacesOfValheim {
} }
} }
if (!RaceInput.Allowed) return;
int state = BossProgressionManager.GetCurrentProgressionState(); int state = BossProgressionManager.GetCurrentProgressionState();
if (Input.GetKeyDown(KeyCode.G)) { TryTransformWithRules(FenrirProgression.GetGKeyRules(state)); return; } if (Input.GetKeyDown(KeyCode.G)) { TryTransformWithRules(FenrirProgression.GetGKeyRules(state)); return; }

View file

@ -0,0 +1,36 @@
using System.Reflection;
using HarmonyLib;
namespace RacesOfValheim
{
/// <summary>
/// Gate for race ability input.
///
/// UnityEngine.Input reads the device directly, so abilities bound to keys or mouse buttons
/// kept firing while the map, the inventory, a chest, the chat or a menu had focus - dragging
/// an item inside a container also swung the transformed attack, for instance. Valheim runs
/// its own controls through Player.TakeInput, which reports false for exactly those states
/// (InventoryGui covers the backpack and chests alike), so mirror that instead of maintaining
/// a parallel list of GUI checks that would drift as the game changes.
/// </summary>
public static class RaceInput
{
// Not public on Player, hence the reflection; resolved once rather than per frame.
private static readonly MethodInfo TakeInputMethod = AccessTools.Method(typeof(Player), "TakeInput");
public static bool Allowed
{
get
{
Player player = Player.m_localPlayer;
if (player == null) return false;
// Fail open: if a game update ever renames the method, abilities stay usable
// rather than silently going dead.
if (TakeInputMethod == null) return true;
return (bool)TakeInputMethod.Invoke(player, null);
}
}
}
}

View file

@ -643,6 +643,8 @@ namespace RacesOfValheim
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_FenrirCurse".GetStableHashCode()); Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_FenrirCurse".GetStableHashCode());
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_AswidStats".GetStableHashCode()); Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_AswidStats".GetStableHashCode());
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_SkeletonStats".GetStableHashCode()); Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_SkeletonStats".GetStableHashCode());
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_SkadiStats".GetStableHashCode());
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_SkadiCooldown".GetStableHashCode());
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>(); ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Human"); if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Human");

View file

@ -93,11 +93,15 @@
<CallTarget Targets="CopyToUnity" Condition="Exists('$(UNITY_FOLDER)')" /> <CallTarget Targets="CopyToUnity" Condition="Exists('$(UNITY_FOLDER)')" />
</Target> </Target>
<Target Name="PackageThunderstore" AfterTargets="Build"> <Target Name="PackageThunderstore" AfterTargets="Build" Condition="'$(Configuration)'=='Release'">
<PropertyGroup>
<PackageOutputDir>$(SolutionDir)dist\</PackageOutputDir>
</PropertyGroup>
<MakeDir Directories="$(PackageOutputDir)" Condition="!Exists('$(PackageOutputDir)')" />
<Message Text="Packaging Thunderstore and Nexus Zips..." Importance="high" /> <Message Text="Packaging Thunderstore and Nexus Zips..." Importance="high" />
<Exec Command="powershell -Command &quot;if (!(Test-Path 'C:\Users\FERDINANDO\Desktop\Pacchetto_Rame\racesofvalheim')) { New-Item -ItemType Directory -Force -Path 'C:\Users\FERDINANDO\Desktop\Pacchetto_Rame\racesofvalheim' }; Compress-Archive -Path '$(TargetDir)$(TargetName).dll', '$(ProjectDir)..\manifest.json', '$(ProjectDir)..\README.md', 'C:\Users\FERDINANDO\Desktop\Pacchetto_Rame\racesofvalheim\icon.png' -DestinationPath 'C:\Users\FERDINANDO\Desktop\Pacchetto_Rame\racesofvalheim\RacesOfValheim_Thunderstore.zip' -Force; Compress-Archive -Path '$(TargetDir)$(TargetName).dll' -DestinationPath 'C:\Users\FERDINANDO\Desktop\Pacchetto_Rame\racesofvalheim\RacesOfValheim_Nexus.zip' -Force&quot;" /> <Exec Command="powershell -NoProfile -Command &quot;Compress-Archive -Path '$(TargetDir)$(TargetName).dll', '$(ProjectDir)..\manifest.json', '$(ProjectDir)..\README.md', '$(ProjectDir)Package\icon.png' -DestinationPath '$(PackageOutputDir)RacesOfValheim_Thunderstore.zip' -Force; Compress-Archive -Path '$(TargetDir)$(TargetName).dll' -DestinationPath '$(PackageOutputDir)RacesOfValheim_Nexus.zip' -Force&quot;" />
<Message Text="Copying DLL to Valheim BepInEx plugins..." Importance="high" /> <Message Text="Copying DLL to Valheim BepInEx plugins..." Importance="high" Condition="Exists('$(VALHEIM_INSTALL)\BepInEx\plugins')" />
<Copy SourceFiles="$(TargetDir)$(TargetName).dll" DestinationFolder="C:\Program Files (x86)\Steam\steamapps\common\Valheim\BepInEx\plugins\" /> <Copy SourceFiles="$(TargetDir)$(TargetName).dll" DestinationFolder="$(VALHEIM_INSTALL)\BepInEx\plugins\" Condition="Exists('$(VALHEIM_INSTALL)\BepInEx\plugins')" />
</Target> </Target>

View file

@ -6,11 +6,21 @@ namespace RacesOfValheim
{ {
public class DrakeFormBehavior : MonoBehaviour public class DrakeFormBehavior : MonoBehaviour
{ {
// Single active instance, read by SkadiDirectedFlightPatch to feed a
// look-direction-based m_moveDir into Character.UpdateFlying every frame.
public static DrakeFormBehavior Active { get; private set; }
private Animator anim; private Animator anim;
private bool isFlying = false; private bool isFlying = false;
private bool isLanding = false; private bool isLanding = false;
private float lastAttackTime = 0f; private float lastAttackTime = 0f;
public bool IsFlying => isFlying;
// Time.time of the last powered/grounded moment. SkadiDirectedFlightPatch holds the form
// level for a short window past this before letting it start sinking.
public float LastPoweredTime;
private SkadiProgression.FormRules formRules; private SkadiProgression.FormRules formRules;
public void Initialize(SkadiProgression.FormRules rules) public void Initialize(SkadiProgression.FormRules rules)
@ -18,15 +28,37 @@ namespace RacesOfValheim
this.formRules = rules; this.formRules = rules;
} }
// formRules is a snapshot taken when the form was entered, so a progression change while
// still transformed (defeating a boss, or the increaseprogression debug command) wouldn't
// grant the attack until the player reverted and transformed again. Re-read the rules for
// the form we're currently in so the unlock applies as soon as the tier is reached.
private bool CanAttackNow()
{
if (formRules == null) return false;
int state = BossProgressionManager.GetCurrentProgressionState();
SkadiProgression.FormRules live = null;
switch (formRules.Form)
{
case SkadiProgression.FormType.Drake: live = SkadiProgression.GetGKeyRules(state); break;
case SkadiProgression.FormType.Moder: live = SkadiProgression.GetHKeyRules(state); break;
case SkadiProgression.FormType.SkeletonDragon: live = SkadiProgression.GetJKeyRules(state); break;
}
return live != null && live.Form == formRules.Form && live.CanAttackInForm;
}
private const float ATTACK_COST = 20f; private const float ATTACK_COST = 20f;
private const float ATTACK_COOLDOWN = 3f; private const float ATTACK_COOLDOWN = 3f;
private void Start() private void Start()
{ {
Active = this;
anim = GetComponentInChildren<Animator>(); anim = GetComponentInChildren<Animator>();
if (Player.m_localPlayer != null) if (Player.m_localPlayer != null)
{ {
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(false); HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_flying").SetValue(false);
} }
} }
@ -35,25 +67,27 @@ namespace RacesOfValheim
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return; if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return;
// Handle Flight Toggle (RMB) - Disabled for Fader // Handle Flight Toggle (RMB) - Disabled for Fader
if (Input.GetMouseButtonDown(1) && formRules != null && formRules.Form != SkadiProgression.FormType.SkeletonDragon) if (RaceInput.Allowed && Input.GetMouseButtonDown(1) && formRules != null && formRules.Form != SkadiProgression.FormType.SkeletonDragon)
{ {
if (!isFlying && !isLanding) if (!isFlying && !isLanding)
{ {
isFlying = true; isFlying = true;
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(true); LastPoweredTime = Time.time;
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_flying").SetValue(true);
} }
else if (isFlying && !isLanding) else if (isFlying && !isLanding)
{ {
isLanding = true; isLanding = true;
isFlying = false; isFlying = false;
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(false); HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_flying").SetValue(false);
} }
else if (isLanding) else if (isLanding)
{ {
// Cancel landing, resume flight // Cancel landing, resume flight
isLanding = false; isLanding = false;
isFlying = true; isFlying = true;
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(true); LastPoweredTime = Time.time;
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_flying").SetValue(true);
} }
} }
@ -88,7 +122,7 @@ namespace RacesOfValheim
} }
// Handle Attack // Handle Attack
if (formRules != null && formRules.CanAttackInForm) if (CanAttackNow() && RaceInput.Allowed)
{ {
if (Input.GetMouseButtonDown(0)) if (Input.GetMouseButtonDown(0))
{ {
@ -345,9 +379,10 @@ namespace RacesOfValheim
private void OnDestroy() private void OnDestroy()
{ {
if (Active == this) Active = null;
if (Player.m_localPlayer != null) if (Player.m_localPlayer != null)
{ {
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(false); HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_flying").SetValue(false);
} }
} }
} }

View file

@ -28,52 +28,58 @@ namespace RacesOfValheim
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")] [HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
public static class Skadi_MultiplayerVisuals_Patch public static class Skadi_MultiplayerVisuals_Patch
{ {
private const string FormSuffix = "_multiplayer";
public static void Postfix(VisEquipment __instance) public static void Postfix(VisEquipment __instance)
{ {
if (!__instance.m_isPlayer) return; if (!__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>(); Player player = __instance.GetComponent<Player>();
if (player == null || player.IsOwner()) return; // Only process remote players if (player == null || player.IsOwner()) return; // Only process remote players
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Skadi")
{
string formName = nview.GetZDO().GetString("RacesOfValheim_SkadiForm", "");
Transform playerVisual = player.transform.Find("Visual");
Transform formBody = player.transform.Find("SkadiBody_Form");
if (!string.IsNullOrEmpty(formName)) {
if (formBody != null && formBody.gameObject.name != formName + "_multiplayer") {
UnityEngine.Object.Destroy(formBody.gameObject);
formBody = null;
}
if (formBody == null) { ZNetView nview = player.GetComponent<ZNetView>();
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(formName); if (nview == null || !nview.IsValid()) return;
if (prefab != null) { if (nview.GetZDO().GetString("RacesOfValheim_Race", "Human") != "Skadi") return;
Transform visual = prefab.transform.Find("Visual");
if (visual != null) { string formName = nview.GetZDO().GetString("RacesOfValheim_SkadiForm", "");
GameObject formInstance = UnityEngine.Object.Instantiate(visual.gameObject, player.transform); Transform playerVisual = player.transform.Find("Visual");
formInstance.name = formName + "_multiplayer"; string wanted = formName + FormSuffix;
if (formName == "Hatchling") formInstance.transform.localPosition = new Vector3(0f, -1.0f, 0f);
else formInstance.transform.localPosition = Vector3.zero; // VisEquipment.UpdateVisuals runs every frame off CustomUpdate, so the spawned model
formInstance.transform.localRotation = Quaternion.identity; // has to be found again by the exact name it was given. This used to search for
} // "SkadiBody_Form" - a name nothing is ever assigned - so the lookup missed every
} // time and a fresh dragon was instantiated each frame. Remote players watched the
} // models pile up on the spot and their client degraded until the Skadi player
if (playerVisual != null) playerVisual.gameObject.SetActive(false); // reverted; the transformed player saw nothing, since owners return above.
} else { // Anything left over from that, or from a previous form, is cleaned up here too.
if (formBody != null) UnityEngine.Object.Destroy(formBody.gameObject); Transform formBody = null;
foreach (Transform child in player.transform)
// Fader form has a different name? "SkadiBody_Form" was used earlier, we just find all children and destroy them if they have "_multiplayer" {
foreach (Transform child in player.transform) { if (!child.name.EndsWith(FormSuffix)) continue;
if (child.name.EndsWith("_multiplayer")) {
UnityEngine.Object.Destroy(child.gameObject); if (formBody == null && child.name == wanted) formBody = child;
} else UnityEngine.Object.Destroy(child.gameObject);
} }
if (playerVisual != null) playerVisual.gameObject.SetActive(true);
if (string.IsNullOrEmpty(formName))
{
if (playerVisual != null) playerVisual.gameObject.SetActive(true);
return;
}
if (formBody == null)
{
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(formName);
Transform visual = prefab != null ? prefab.transform.Find("Visual") : null;
if (visual != null)
{
GameObject formInstance = UnityEngine.Object.Instantiate(visual.gameObject, player.transform);
formInstance.name = wanted;
formInstance.transform.localPosition = formName == "Hatchling" ? new Vector3(0f, -1.0f, 0f) : Vector3.zero;
formInstance.transform.localRotation = Quaternion.identity;
} }
} }
if (playerVisual != null) playerVisual.gameObject.SetActive(false);
} }
} }
@ -98,6 +104,10 @@ namespace RacesOfValheim
if (rules.FreezingToCold) if (rules.FreezingToCold)
{ {
// Strip any real Freezing that may already be active (e.g. applied
// before this tier's conversion kicked in) so it can't linger
// alongside the converted Cold status.
__instance.RemoveStatusEffect("Freezing".GetStableHashCode(), true);
nameHash = "Cold".GetStableHashCode(); nameHash = "Cold".GetStableHashCode();
} }
} }
@ -106,6 +116,73 @@ namespace RacesOfValheim
} }
} }
// SE_SkadiStats grants a "Resistant" (or higher) Frost damage modifier from tier 1 onward,
// exactly like drinking a Frost Resistance potion. Valheim's own Player.UpdateEnvStatusEffects
// checks that same Frost damage modifier before deciding whether to apply Cold/Freezing at
// all, and skips both entirely once the character is Frost-resistant. That means real Mountain
// exposure (which applies Freezing, not Cold, per vanilla rules) never even reaches
// 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.
[HarmonyPatch(typeof(Player), "UpdateEnvStatusEffects")]
public static class SkadiEnvCheckScope
{
public static bool Active = false;
public static void Prefix(Player __instance)
{
Active = __instance == Player.m_localPlayer && SkadiRace.Instance != null && SkadiRace.Instance.IsSkadi();
}
public static void Postfix()
{
Active = false;
}
}
[HarmonyPatch(typeof(Character), "GetDamageModifiers")]
public static class SkadiEnvFrostModifierPatch
{
public static void Postfix(Character __instance, ref HitData.DamageModifiers __result)
{
if (SkadiEnvCheckScope.Active && __instance == Player.m_localPlayer)
{
__result.m_frost = HitData.DamageModifier.Normal;
}
}
}
// Valheim's Player.UpdateEnvStatusEffects always tries RemoveStatusEffect(Cold, quiet:true)
// as the first step of applying Freezing. Since SkadiSEManPatch redirects Freezing into Cold,
// that removal would strip our converted Cold status every other frame (a permanent
// add/remove flicker that cancels the buff out). Blocking just this "quiet" removal for the
// FreezingToCold player forces Valheim to always fall through to AddStatusEffect(Freezing,...),
// which SkadiSEManPatch converts to a stable, non-resetting Cold re-application instead.
[HarmonyPatch(typeof(SEMan), "RemoveStatusEffect", new System.Type[] { typeof(int), typeof(bool) })]
public static class SkadiColdRemovalGuardPatch
{
public static bool Prefix(SEMan __instance, int nameHash, bool quiet, ref bool __result)
{
if (quiet && nameHash == "Cold".GetStableHashCode())
{
Character character = Traverse.Create(__instance).Field<Character>("m_character").Value;
if (character == Player.m_localPlayer && SkadiRace.Instance != null && SkadiRace.Instance.IsSkadi())
{
var rules = SkadiProgression.GetRules(BossProgressionManager.GetCurrentProgressionState());
if (rules.FreezingToCold && !rules.ImmuneToFreezing)
{
__result = false;
return false;
}
}
}
return true;
}
}
[HarmonyPatch(typeof(Character), "ApplyDamage")] [HarmonyPatch(typeof(Character), "ApplyDamage")]
public static class SkadiDamagePatch public static class SkadiDamagePatch
{ {
@ -129,6 +206,79 @@ namespace RacesOfValheim
// DrakeFormBehavior flips the player into Character's native flying-creature movement
// (m_flying = true) instead of the old debug-fly noclip, which lets us feed it a full 3D
// move direction. Character.UpdateFlying normally reads whatever m_moveDir the vanilla input
// pipeline last wrote (ground-plane WASD relative to camera yaw only); this patch overwrites
// it every frame with the camera's actual look direction (pitch included) so the player always
// glides toward wherever the mouse is aiming, with W adding a speed boost (m_run) on top of the
// base glide speed instead of being required just to move.
[HarmonyPatch(typeof(Character), "UpdateFlying")]
public static class SkadiDirectedFlightPatch
{
private const float TURN_SPEED = 120f;
private const float GLIDE_SPEED = 5f;
private const float BOOST_SPEED = 12f;
private const float HOVER_SECONDS = 2f;
// Tangent of the unpowered descent angle: 0.4 sinks at roughly 22 degrees below level.
private const float DESCENT_SLOPE = 0.4f;
public static void Prefix(Character __instance)
{
if (__instance != Player.m_localPlayer) return;
DrakeFormBehavior form = DrakeFormBehavior.Active;
if (form == null || !form.IsFlying) return;
var traverse = Traverse.Create(__instance);
Vector3 lookDir = Player.m_localPlayer.GetLookDir();
bool boost = RaceInput.Allowed && Input.GetKey(KeyCode.W);
bool onGround = __instance.IsOnGround();
traverse.Field("m_run").SetValue(boost);
traverse.Field("m_flyFastSpeed").SetValue(BOOST_SPEED);
// UpdateFlying rotates the body toward m_moveDir on its own, but at m_flyTurnSpeed,
// which sits at Character's 12 deg/s default because the Player prefab was never set
// up as a flying creature - a 90 degree turn would take over seven seconds, so the
// model reads as not turning at all. Give it a speed that suits a flying mount.
traverse.Field("m_flyTurnSpeed").SetValue(TURN_SPEED);
// Powered flight and ground contact both refresh the hover window.
if (boost || onGround) form.LastPoweredTime = Time.time;
Vector3 moveDir = lookDir;
float coastSpeed;
if (onGround || Time.time - form.LastPoweredTime < HOVER_SECONDS)
{
// Holding station: on the ground this keeps a touchdown from sliding the player
// forward forever, and in the air it gives the beat of level flight before the
// form starts to sink. m_moveDir stays full length so the body still turns to
// face the camera, and zeroing the speed (rather than the rigidbody velocity)
// avoids fighting the AddForce UpdateFlying queues, which caused visible jitter.
coastSpeed = 0f;
}
else
{
// Unpowered flight is a glide, not a hover with a joystick: drift along the
// heading the camera faces while losing height, so aiming at the sky without
// holding W no longer climbs.
Vector3 heading = new Vector3(lookDir.x, 0f, lookDir.z);
if (heading.sqrMagnitude < 0.0001f)
{
heading = __instance.transform.forward;
heading.y = 0f;
}
moveDir = (heading.normalized + Vector3.down * DESCENT_SLOPE).normalized;
coastSpeed = GLIDE_SPEED;
}
traverse.Field("m_moveDir").SetValue(moveDir);
traverse.Field("m_flySlowSpeed").SetValue(coastSpeed);
}
}
[HarmonyPatch(typeof(Humanoid), "StartAttack")] [HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class SkadiAttackPatch public static class SkadiAttackPatch
{ {

View file

@ -11,6 +11,7 @@ namespace RacesOfValheim
public static SkadiRace Instance; public static SkadiRace Instance;
public static SE_SkadiStats skadiCurseSE; public static SE_SkadiStats skadiCurseSE;
public static SE_FormCooldown skadiCdSE; public static SE_FormCooldown skadiCdSE;
public static SE_SkadiForm skadiFormSE;
private float auraTimer = 0f; private float auraTimer = 0f;
private float lastSpellTime = 0f; private float lastSpellTime = 0f;
@ -18,6 +19,8 @@ namespace RacesOfValheim
private bool isTransformed = false; private bool isTransformed = false;
private bool isTransformingSequence = false; private bool isTransformingSequence = false;
private SkadiProgression.FormRules activeRules = null; private SkadiProgression.FormRules activeRules = null;
// Time.time at which a timed form drops; 0 means the current form has no time limit.
private float formExpireTime = 0f;
private float lastAuraTime = 0f; private float lastAuraTime = 0f;
private GameObject frostAuraVFX = null; private GameObject frostAuraVFX = null;
@ -47,18 +50,33 @@ namespace RacesOfValheim
ItemManager.Instance.AddStatusEffect(skadiStats); ItemManager.Instance.AddStatusEffect(skadiStats);
skadiCurseSE = skadiStats.StatusEffect as SE_SkadiStats; skadiCurseSE = skadiStats.StatusEffect as SE_SkadiStats;
// Timed forms and their cooldown are Moder's, so they carry her trophy rather than the
// drake one used for the passive blessing.
Sprite dragonIcon = GetTrophyIcon("TrophyDragonQueen") ?? GetTrophyIcon("TrophyHatchling");
skadiCdSE = ScriptableObject.CreateInstance<SE_FormCooldown>(); skadiCdSE = ScriptableObject.CreateInstance<SE_FormCooldown>();
skadiCdSE.name = "SE_SkadiCooldown"; skadiCdSE.name = "SE_SkadiCooldown";
skadiCdSE.m_name = "Dragon Form Cooldown"; skadiCdSE.m_name = "Dragon Form Cooldown";
if (drakeTrophy != null) skadiCdSE.m_icon = dragonIcon;
{
ItemDrop trophyDrop = drakeTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
skadiCdSE.m_icon = trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(skadiCdSE, fixReference: false)); ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(skadiCdSE, fixReference: false));
skadiFormSE = ScriptableObject.CreateInstance<SE_SkadiForm>();
skadiFormSE.name = "SE_SkadiForm";
skadiFormSE.m_name = "Dragon Form";
skadiFormSE.m_tooltip = "Your dragon shape holds for a while longer.";
skadiFormSE.m_icon = dragonIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(skadiFormSE, fixReference: false));
}
private static Sprite GetTrophyIcon(string prefabName)
{
GameObject trophy = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName)?.gameObject;
ItemDrop drop = trophy != null ? trophy.GetComponent<ItemDrop>() : null;
if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0)
{
return drop.m_itemData.m_shared.m_icons[0];
}
return null;
} }
@ -132,13 +150,26 @@ namespace RacesOfValheim
} }
} }
if (rules.ColdSpell) if (rules.ColdSpell && RaceInput.Allowed)
{ {
HandleColdSpell(rules); HandleColdSpell(rules);
} }
if (isTransformingSequence) return; if (isTransformingSequence) return;
// Forms with a DurationMinutes budget drop on their own once it runs out, which is
// also what starts their cooldown - without this the timed tiers never expired.
if (isTransformed && formExpireTime > 0f && Time.time >= formExpireTime)
{
formExpireTime = 0f;
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Your dragon form fades.");
StartCoroutine(RevertToHumanRoutine());
return;
}
// Form keys and the debug dump are ability input: they stay inert while a GUI has focus.
if (!RaceInput.Allowed) return;
int state = BossProgressionManager.GetCurrentProgressionState(); int state = BossProgressionManager.GetCurrentProgressionState();
if (Input.GetKeyDown(KeyCode.G)) { TryTransformWithRules(SkadiProgression.GetGKeyRules(state)); return; } if (Input.GetKeyDown(KeyCode.G)) { TryTransformWithRules(SkadiProgression.GetGKeyRules(state)); return; }
if (Input.GetKeyDown(KeyCode.H)) { TryTransformWithRules(SkadiProgression.GetHKeyRules(state)); return; } if (Input.GetKeyDown(KeyCode.H)) { TryTransformWithRules(SkadiProgression.GetHKeyRules(state)); return; }
@ -230,7 +261,7 @@ namespace RacesOfValheim
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return; if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return;
if (isTransformed) return; // Do not cast human spell while in dragon form if (isTransformed) return; // Do not cast human spell while in dragon form
// Middle Mouse Button to cast (Kick) // Middle Mouse Button to cast
if (Input.GetMouseButtonDown(2)) if (Input.GetMouseButtonDown(2))
{ {
float cooldown = rules.ImprovedColdSpell ? 2.0f : 1.5f; float cooldown = rules.ImprovedColdSpell ? 2.0f : 1.5f;
@ -246,10 +277,11 @@ namespace RacesOfValheim
lastSpellTime = Time.time; lastSpellTime = Time.time;
var zanim = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field<ZSyncAnimation>("m_zanim").Value; var zanim = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field<ZSyncAnimation>("m_zanim").Value;
if (zanim != null) if (zanim != null)
{ {
// Forcing secondary attack trigger, which is kick when unarmed // Raised-arms Galdr cast gesture instead of the unarmed kick, so the cast
zanim.SetTrigger("secondary"); // reads as a spell instead of a leg swing near the ground.
zanim.SetTrigger("galdr_cast");
} }
StartCoroutine(ColdSpellKickCoroutine(rules)); StartCoroutine(ColdSpellKickCoroutine(rules));
@ -258,7 +290,7 @@ namespace RacesOfValheim
private IEnumerator ColdSpellKickCoroutine(SkadiProgression.FormRules rules) private IEnumerator ColdSpellKickCoroutine(SkadiProgression.FormRules rules)
{ {
// Wait for the kick animation to reach the extension point // Wait for the cast animation to reach the release point
yield return new WaitForSeconds(0.4f); yield return new WaitForSeconds(0.4f);
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) yield break; if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) yield break;
@ -287,16 +319,16 @@ namespace RacesOfValheim
{ {
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) break; if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) break;
// Spawn from the foot (low position, forward) // Spawn from chest height, forward
Vector3 lookDir = Player.m_localPlayer.GetLookDir(); Vector3 lookDir = Player.m_localPlayer.GetLookDir();
// Add a small spread for the improved blast // Add a small spread for the improved blast
if (rules.ImprovedColdSpell && i > 0) if (rules.ImprovedColdSpell && i > 0)
{ {
lookDir = Quaternion.Euler(UnityEngine.Random.Range(-5f, 5f), UnityEngine.Random.Range(-5f, 5f), 0f) * lookDir; lookDir = Quaternion.Euler(UnityEngine.Random.Range(-5f, 5f), UnityEngine.Random.Range(-5f, 5f), 0f) * lookDir;
} }
Vector3 spawnPos = Player.m_localPlayer.transform.position + Vector3.up * 0.4f + lookDir * 0.6f; Vector3 spawnPos = Player.m_localPlayer.transform.position + Vector3.up * 1.4f + lookDir * 0.6f;
GameObject projInstance = Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(lookDir)); GameObject projInstance = Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(lookDir));
@ -588,10 +620,33 @@ namespace RacesOfValheim
else if (prefabName == "Fader") Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are Fader!"); else if (prefabName == "Fader") Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are Fader!");
isTransformed = true; isTransformed = true;
StartFormTimer(rules);
} }
} }
} }
// Drives both the expiry check in Update and the HUD icon: the status effect exists purely
// so Valheim draws Moder's trophy with its own countdown next to the minimap.
private void StartFormTimer(SkadiProgression.FormRules rules)
{
int hash = "SE_SkadiForm".GetStableHashCode();
SEMan seman = Player.m_localPlayer.GetSEMan();
seman.RemoveStatusEffect(hash, true);
if (rules.DurationMinutes <= 0f)
{
formExpireTime = 0f;
return;
}
float seconds = rules.DurationMinutes * 60f;
formExpireTime = Time.time + seconds;
seman.AddStatusEffect(hash, true);
StatusEffect se = seman.GetStatusEffect(hash);
if (se != null) se.m_ttl = seconds;
}
private void ExecuteReversion() private void ExecuteReversion()
{ {
Transform playerVisual = Player.m_localPlayer.transform.Find("Visual"); Transform playerVisual = Player.m_localPlayer.transform.Find("Visual");
@ -614,6 +669,8 @@ namespace RacesOfValheim
} }
isTransformed = false; isTransformed = false;
formExpireTime = 0f;
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_SkadiForm".GetStableHashCode(), true);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You returned to human form."); Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You returned to human form.");
if (activeRules != null && activeRules.CooldownMinutes > 0) if (activeRules != null && activeRules.CooldownMinutes > 0)

View file

@ -4,6 +4,12 @@ using UnityEngine;
namespace RacesOfValheim namespace RacesOfValheim
{ {
// Timed dragon forms. m_ttl is set when the form is entered, which is all Valheim needs to
// render the countdown: StatusEffect.GetIconText() prints the remaining time by itself.
public class SE_SkadiForm : StatusEffect
{
}
public class SE_SkadiStats : SE_Stats public class SE_SkadiStats : SE_Stats
{ {
public override void Setup(Character character) public override void Setup(Character character)

View file

@ -119,14 +119,17 @@ namespace RacesOfValheim
{ {
if (!IsTrol()) return; if (!IsTrol()) return;
if (Input.GetKeyDown(KeyCode.G)) if (RaceInput.Allowed)
{ {
TryThrowRock(); if (Input.GetKeyDown(KeyCode.G))
} {
TryThrowRock();
}
if (Input.GetKeyDown(KeyCode.H)) if (Input.GetKeyDown(KeyCode.H))
{ {
TryTrueForm(); TryTrueForm();
}
} }
// Check log durability // Check log durability

7
NuGet.Config Normal file
View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
<add key="bepinex" value="https://nuget.bepinex.dev/v3/index.json" />
</packageSources>
</configuration>

View file

@ -81,13 +81,18 @@ This mod currently introduces 6 custom races:
### Skadi Progression ### Skadi Progression
- **Base (No Bosses)**: Immune to Cold, Bonus Frost Damage, 50% Frost Resistance. - **Base (No Bosses)**: Immune to Cold, Bonus Frost Damage, 50% Frost Resistance.
- **Eikthyr**: +20% Eitr Regen, Freezing to Cold, Cold Spell. - **Eikthyr**: +20% Eitr Regen, Freezing to Cold, Cold Spell (Middle Mouse).
- **The Elder**: Drake Form (Cannot attack). - **The Elder**: Drake Form ('G' Key) (Cannot attack).
- **Bonemass**: Drake Form (Can attack). - **Bonemass**: Drake Form ('G' Key) (Can attack).
- **Moder**: Moder Form (1 min duration, 10 min cooldown). - **Moder**: Moder Form ('H' Key) (1 min duration, 10 min cooldown).
- **Yagluth**: Improved Cold Spell. Moder Form (1 min duration, 5 min cooldown). - **Yagluth**: Improved Cold Spell. Moder Form ('H' Key) (1 min duration, 5 min cooldown).
- **The Queen**: Moder Form (Unlimited duration, no cooldown). - **The Queen**: Moder Form ('H' Key) (Unlimited duration, no cooldown).
- **Fader**: Skeleton Dragon Form. - **Fader**: Skeleton Dragon Form ('J' Key).
While transformed, Right Mouse toggles flight. You glide toward wherever you are aiming; hold W
to power forward and climb. Let go and the form holds level for a couple of seconds before
settling into a gentle descent. Timed forms show their remaining seconds, and their cooldown,
as a Moder trophy icon beside the minimap.
### Skeleton Progression ### Skeleton Progression
- **Base (No Bosses)**: +50 Max Health. Undead Diet (Cannot eat mortal food, no stamina bar). - **Base (No Bosses)**: +50 Max Health. Undead Diet (Cannot eat mortal food, no stamina bar).