RacesOfValheim/JotunnModStub/Skadi/SkadiRace.cs
Ferdinando 834d6647fd chore(release): v1.4.19 - eye height, remote forms, food refresh, faction retaliation
Race body scale moved the model and not the camera: Character.m_eye hangs
off the unscaled root, so a Trol or a Dvergar changed height for everyone
but themselves. RaceEyeHeight moves the eye by whatever scale the Visual
is wearing, for every player, so aim rays follow too.

Remote copies of a Fenrir form had no one writing to their Animator and
stood in the controller's default state, sliding. RemoteFenrirAnimator
mirrors the four local behaviours off the player's own replicated
animator, the way RemoteSkadiAnimator already did for Skadi.

Player.Food.m_time is time remaining, not time elapsed: the Aswid, Trenta
and Draugh repeat-meal branches all set it to 0 and expired the slot they
meant to renew, and left the nutrition values stale. RaceFoodRefresh does
what vanilla's own branch does, in one place instead of three. The Trenta
prefix now reports __result, or a working refresh would have renewed the
slot without consuming the seed.

Aswid devour was gated by one timestamp shared by every corpse, so a pack
killed at once fed the player once; it is now per corpse, floored at a
second, and a refused meal says $msg_nomore.

MonsterAI.UpdateTarget discards any target IsEnemy refuses, so a truced
mob could not retaliate at all - it stood still or fled. RaceGrudge
records the hit on the AI owner's client and both truce postfixes stand
down for that pair. The Aswid drain and the Skadi frost aura now skip
kin, as the Skeleton's fire aura already did, or an always-on aura would
hold every truce permanently broken.

Faction sets matched exact prefab names with families half-listed:
added Skeleton_NoArcher and Draugr_Ranged to the Swamp, Greyling to the
Black Forest.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-20 08:26:22 +02:00

794 lines
36 KiB
C#

using System;
using System.Collections;
using UnityEngine;
using Jotunn.Managers;
using Jotunn.Entities;
namespace RacesOfValheim
{
public class SkadiRace : MonoBehaviour
{
public static SkadiRace Instance;
public static SE_SkadiStats skadiCurseSE;
public static SE_FormCooldown skadiCdSE;
public static SE_SkadiForm skadiFormSE;
private float auraTimer = 0f;
private float lastSpellTime = 0f;
private GameObject currentTransformation;
private bool isTransformed = false;
private bool isTransformingSequence = false;
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 GameObject frostAuraVFX = null;
// Cold Spell tuning. Damage is 15 + 8 per progression state, so it runs from roughly 31 at
// Eikthyr to 79 at Fader - deliberately a notch under the melee options of the other races
// at each tier, which is the trade for hitting at range on a short cooldown.
//
// All values below read from SkadiConfig (BepInEx Config, see SkadiConfig.cs) rather than
// being fixed constants, so they can be retuned from Configuration Manager without a
// rebuild - see CONFIGURATION-MANAGER-HOWTO.md.
public const string SPELL_COOLDOWN_SE = "SE_SkadiSpellCooldown";
public const string ATTACK_COOLDOWN_SE = "SE_SkadiAttackCooldown";
private static float SPELL_STAMINA_COST => SkadiConfig.SpellStaminaCost.Value;
private static float SPELL_COOLDOWN => SkadiConfig.SpellCooldown.Value;
private static float IMPROVED_SPELL_COOLDOWN => SkadiConfig.ImprovedSpellCooldown.Value;
private static float SPELL_BASE_DAMAGE => SkadiConfig.SpellBaseDamage.Value;
private static float SPELL_DAMAGE_PER_STATE => SkadiConfig.SpellDamagePerState.Value;
private static int IMPROVED_SPELL_SHARDS => SkadiConfig.ImprovedSpellShards.Value;
// The improved cast spreads 1.6 casts worth of damage over its shards: wider, not stronger.
private static float IMPROVED_SPELL_DAMAGE_BUDGET => SkadiConfig.ImprovedSpellDamageBudget.Value;
private void Awake()
{
Instance = this;
}
public void CreateModAssets()
{
// The reagent goes first: the faction merchant catalogue resolves its entries by prefab
// name, so Greater Frost Heart has to exist before a Fenring_Cultist is ever set up as a
// bench.
SkadiFrostHeart.Register();
SkadiGolem.Register();
var se = ScriptableObject.CreateInstance<SE_SkadiStats>();
se.name = "SE_SkadiStats";
se.m_name = "Skadi's Blessing";
// Icon
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)
{
se.m_icon = trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
CustomStatusEffect skadiStats = new CustomStatusEffect(se, fixReference: false);
ItemManager.Instance.AddStatusEffect(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 = GetItemIcon("TrophyDragonQueen") ?? GetItemIcon("TrophyHatchling");
skadiCdSE = ScriptableObject.CreateInstance<SE_FormCooldown>();
skadiCdSE.name = "SE_SkadiCooldown";
skadiCdSE.m_name = "Dragon Form Cooldown";
skadiCdSE.m_icon = dragonIcon;
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));
// Per-ability cooldowns. Each gets its own icon so a spell on cooldown reads
// differently from a dragon attack on cooldown at a glance.
var spellCd = ScriptableObject.CreateInstance<SE_SkadiAbilityCooldown>();
spellCd.name = SPELL_COOLDOWN_SE;
spellCd.m_name = "Cold Spell";
spellCd.m_tooltip = "The frost must gather again before you may cast.";
spellCd.m_icon = GetItemIcon("StaffIceShards") ?? dragonIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(spellCd, fixReference: false));
var attackCd = ScriptableObject.CreateInstance<SE_SkadiAbilityCooldown>();
attackCd.name = ATTACK_COOLDOWN_SE;
attackCd.m_name = "Dragon Attack";
attackCd.m_tooltip = "Your dragon shape must ready itself to strike again.";
attackCd.m_icon = GetItemIcon("TrophyHatchling") ?? dragonIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(attackCd, fixReference: false));
}
// Drives the HUD countdown: Valheim prints the remaining time on any status effect whose
// m_ttl is set, so the cooldown only has to exist for the icon to tick down by itself.
public static void ApplyCooldownIcon(string effectName, float seconds)
{
if (Player.m_localPlayer == null || seconds <= 0f) return;
int hash = effectName.GetStableHashCode();
SEMan seman = Player.m_localPlayer.GetSEMan();
seman.RemoveStatusEffect(hash, true);
seman.AddStatusEffect(hash, true);
StatusEffect se = seman.GetStatusEffect(hash);
if (se != null) se.m_ttl = seconds;
}
private static Sprite GetItemIcon(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;
}
public bool IsSkadi()
{
return IsLocalSkadi();
}
/// <summary>
/// The same check, reachable without an Instance - which the golem and the cave-building
/// watcher both need, since they run from static context.
/// </summary>
public static bool IsLocalSkadi()
{
return Player.m_localPlayer != null &&
Player.m_localPlayer.m_customData.ContainsKey("Race") &&
Player.m_localPlayer.m_customData["Race"] == "Skadi";
}
private void Update()
{
if (!IsSkadi()) return;
if (Player.m_localPlayer.IsDead() && isTransformed)
{
ExecuteReversion();
}
var rules = SkadiProgression.GetRules(BossProgressionManager.GetCurrentProgressionState());
// Update the stats SE
if (skadiCurseSE != null)
{
int auraHash = skadiCurseSE.name.GetStableHashCode();
SEMan seman = Player.m_localPlayer.GetSEMan();
skadiCurseSE.UpdateStats(rules);
if (!seman.HaveStatusEffect(auraHash))
{
seman.AddStatusEffect(auraHash, true);
}
// SEMan.AddStatusEffect stores a Clone() of the prototype, so updating
// skadiCurseSE alone only changed the copy that gets stamped out at the next add:
// the aura already running on the player kept whatever tier it was born with.
// Beating a boss mid-session left the old frost modifier and eitr regen in place
// until the effect was re-added (race reselection or a relog) - most visibly at
// the Queen, where Immune never replaced Resistant. Refresh the live one as well;
// UpdateStats is a no-op unless the tier actually moved a value.
SE_SkadiStats liveAura = seman.GetStatusEffect(auraHash) as SE_SkadiStats;
if (liveAura != null) liveAura.UpdateStats(rules);
}
if (rules.FrostAura)
{
EnsureFrostAuraVFX(true);
if (Time.time - lastAuraTime >= SkadiConfig.AuraTickInterval.Value)
{
ApplyColdAura();
lastAuraTime = Time.time;
}
}
else
{
EnsureFrostAuraVFX(false);
}
if (rules.EitrRegenMultiplier > 1f && !Player.m_localPlayer.IsDead())
{
try
{
var eitrTimerField = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_eitrRegenTimer");
if (eitrTimerField.FieldExists())
{
float currentTimer = eitrTimerField.GetValue<float>();
if (currentTimer > 0f)
{
float bonus = rules.EitrRegenMultiplier - 1f;
if (bonus > 0f && bonus < 1f)
{
float targetTime = 1f - bonus;
float requiredSpeed = 1f / targetTime;
float additionalSpeed = requiredSpeed - 1f;
eitrTimerField.SetValue(currentTimer - (additionalSpeed * Time.deltaTime));
}
}
}
}
catch (Exception e)
{
// Ignore, to prevent breaking the rest of the Update loop
}
}
if (rules.ColdSpell && RaceInput.Allowed)
{
HandleColdSpell(rules);
}
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();
if (SkadiConfig.DrakeFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(SkadiProgression.GetGKeyRules(state)); return; }
if (SkadiConfig.ModerFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(SkadiProgression.GetHKeyRules(state)); return; }
if (SkadiConfig.FaderFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(SkadiProgression.GetJKeyRules(state)); return; }
// Debug Dump
if (Input.GetKeyDown(KeyCode.F8))
{
DumpPrefabDebugInfo("Dragon");
DumpPrefabDebugInfo("Hatchling");
DumpPrefabDebugInfo("Fader");
if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Dumped Dragon/Drake/Fader debug info to console!");
}
}
private void DumpPrefabDebugInfo(string prefabName)
{
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"{prefabName} prefab not found!");
return;
}
Jotunn.Logger.LogInfo($"=== {prefabName.ToUpper()} DEBUG INFO ===");
Animator anim = prefab.GetComponentInChildren<Animator>();
if (anim != null)
{
Jotunn.Logger.LogInfo("--- Animator Parameters ---");
foreach (UnityEngine.AnimatorControllerParameter param in anim.parameters)
{
Jotunn.Logger.LogInfo($"Param: {param.name} (Type: {param.type})");
}
}
Humanoid humanoid = prefab.GetComponent<Humanoid>();
if (humanoid != null)
{
Jotunn.Logger.LogInfo("--- Weapons (Default Items) ---");
if (humanoid.m_defaultItems != null)
{
foreach (GameObject item in humanoid.m_defaultItems)
{
if (item == null) continue;
ItemDrop drop = item.GetComponent<ItemDrop>();
if (drop != null)
{
var attack = drop.m_itemData.m_shared.m_attack;
Jotunn.Logger.LogInfo($"Weapon Prefab: {item.name}");
Jotunn.Logger.LogInfo($" - Attack Anim: {attack.m_attackAnimation}");
if (attack.m_attackProjectile != null)
Jotunn.Logger.LogInfo($" - Projectile: {attack.m_attackProjectile.name}");
}
}
}
Jotunn.Logger.LogInfo("--- Random Weapons ---");
if (humanoid.m_randomWeapon != null)
{
foreach (var item in humanoid.m_randomWeapon)
{
if (item == null) continue;
ItemDrop drop = item.GetComponent<ItemDrop>();
if (drop != null)
{
var attack = drop.m_itemData.m_shared.m_attack;
Jotunn.Logger.LogInfo($"Random Weapon Prefab: {item.name}");
Jotunn.Logger.LogInfo($" - Attack Anim: {attack.m_attackAnimation}");
if (attack.m_attackProjectile != null)
Jotunn.Logger.LogInfo($" - Projectile: {attack.m_attackProjectile.name}");
}
}
}
}
ZSFX[] sfxs = prefab.GetComponentsInChildren<ZSFX>(true);
Jotunn.Logger.LogInfo("--- Sounds (ZSFX) ---");
foreach (ZSFX sfx in sfxs)
{
Jotunn.Logger.LogInfo($"Sound: {sfx.gameObject.name}");
}
Jotunn.Logger.LogInfo($"=== END {prefabName.ToUpper()} DEBUG INFO ===");
}
private void HandleColdSpell(SkadiProgression.FormRules rules)
{
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return;
if (isTransformed) return; // Do not cast human spell while in dragon form
// Middle Mouse Button to cast, by default - rebindable via SkadiConfig.ColdSpellKey.
// On a gamepad, the secondary attack button (the pad's own middle-mouse equivalent).
if (SkadiConfig.ColdSpellKey.Value.IsDownIgnoringHeldKeys() || RaceInput.PadAttackDown(2))
{
// The improved cast is a burst rather than a rapid-fire, so it waits longer.
float cooldown = rules.ImprovedColdSpell ? IMPROVED_SPELL_COOLDOWN : SPELL_COOLDOWN;
if (Time.time - lastSpellTime < cooldown) return;
// Stamina, never eitr: the spell unlocks at Eikthyr but eitr food only exists from
// the Mistlands onward, so the old HaveEitr gate left it unusable for five tiers.
if (!Player.m_localPlayer.HaveStamina(SPELL_STAMINA_COST))
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Not enough stamina");
return;
}
Player.m_localPlayer.UseStamina(SPELL_STAMINA_COST);
lastSpellTime = Time.time;
ApplyCooldownIcon(SPELL_COOLDOWN_SE, cooldown);
var zanim = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field<ZSyncAnimation>("m_zanim").Value;
if (zanim != null)
{
// "galdr_cast" is not one of the triggers Valheim actually defines, so it
// never fired and the unarmed kick stayed. "gpower" is the guardian power
// raise: both arms up, which reads as casting rather than a leg swing.
RaceInput.SuppressGuardianPowerBriefly();
zanim.SetTrigger("gpower");
}
StartCoroutine(ColdSpellKickCoroutine(rules));
}
}
private IEnumerator ColdSpellKickCoroutine(SkadiProgression.FormRules rules)
{
// Wait for the cast animation to reach the release point
yield return new WaitForSeconds(0.4f);
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) yield break;
GameObject staffPrefab = PrefabManager.Cache.GetPrefab<GameObject>("StaffIceShards");
if (staffPrefab == null) yield break;
ItemDrop staffDrop = staffPrefab.GetComponent<ItemDrop>();
if (staffDrop == null) yield break;
string projName = rules.ImprovedColdSpell ? "hatchling_cold_projectile" : null;
GameObject projPrefab = null;
if (projName != null)
{
projPrefab = PrefabManager.Cache.GetPrefab<GameObject>(projName);
}
if (projPrefab == null)
{
projPrefab = staffDrop.m_itemData.m_shared.m_attack.m_attackProjectile; // Default Staff of Frost projectile
}
if (projPrefab == null) yield break;
int count = rules.ImprovedColdSpell ? IMPROVED_SPELL_SHARDS : 1;
// The staff prefab is borrowed for its projectile visuals and velocity only. Its damage
// is Mistlands-tier, which the spell used to hand out in full from Eikthyr onward, and
// once per shard - so the improved cast was a ten times nuke rather than a wider one.
// Scale with progression instead, and split one budget across the shards.
int state = BossProgressionManager.GetCurrentProgressionState();
float castDamage = SPELL_BASE_DAMAGE + SPELL_DAMAGE_PER_STATE * state;
if (count > 1) castDamage *= IMPROVED_SPELL_DAMAGE_BUDGET;
float shardDamage = castDamage / count;
for (int i = 0; i < count; i++)
{
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) break;
// Spawn from chest height, forward
Vector3 lookDir = Player.m_localPlayer.GetLookDir();
// Add a small spread for the improved blast
if (rules.ImprovedColdSpell && i > 0)
{
lookDir = Quaternion.Euler(UnityEngine.Random.Range(-5f, 5f), UnityEngine.Random.Range(-5f, 5f), 0f) * lookDir;
}
Vector3 spawnPos = Player.m_localPlayer.transform.position + Vector3.up * 1.4f + lookDir * 0.6f;
GameObject projInstance = Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(lookDir));
Projectile proj = projInstance.GetComponent<Projectile>();
if (proj != null)
{
HitData hitData = new HitData();
hitData.m_damage.m_frost = shardDamage;
hitData.SetAttacker(Player.m_localPlayer);
// Before Setup, which is what copies the skill and its amount onto the
// projectile. Same split as the damage budget above, and for the same reason.
SkadiMagicSkill.TagCast(hitData, count);
proj.Setup(Player.m_localPlayer, lookDir * staffDrop.m_itemData.m_shared.m_attack.m_projectileVel, -1f, hitData, staffDrop.m_itemData, null);
}
if (count > 1) yield return new WaitForSeconds(0.05f);
}
}
private void EnsureFrostAuraVFX(bool enable)
{
if (Player.m_localPlayer == null) return;
if (enable)
{
if (frostAuraVFX == null)
{
frostAuraVFX = new GameObject("SkadiFrostAuraVFX");
frostAuraVFX.transform.SetParent(Player.m_localPlayer.transform, false);
frostAuraVFX.transform.localPosition = new Vector3(0, 1f, 0); // Center of player
ParticleSystem ps = frostAuraVFX.AddComponent<ParticleSystem>();
var main = ps.main;
main.duration = 5f;
main.loop = true;
main.startLifetime = 3f;
main.startSpeed = 0.2f; // Slow moving
main.startSize = new ParticleSystem.MinMaxCurve(0.005f, 0.01f); // 1cm max
main.startColor = new Color(0.7f, 0.9f, 1f, 0.4f); // Light blue, semi-transparent
main.maxParticles = 300;
main.simulationSpace = ParticleSystemSimulationSpace.World; // Leaves a trail when walking
var emission = ps.emission;
emission.rateOverTime = 90; // Dense mist
var shape = ps.shape;
shape.shapeType = ParticleSystemShapeType.Sphere;
shape.radius = 3f; // 3 meters radius
var colorOverLifetime = ps.colorOverLifetime;
colorOverLifetime.enabled = true;
Gradient grad = new Gradient();
grad.SetKeys(
new GradientColorKey[] { new GradientColorKey(Color.white, 0.0f), new GradientColorKey(Color.white, 1.0f) },
new GradientAlphaKey[] { new GradientAlphaKey(0.0f, 0.0f), new GradientAlphaKey(1.0f, 0.2f), new GradientAlphaKey(1.0f, 0.8f), new GradientAlphaKey(0.0f, 1.0f) }
);
colorOverLifetime.color = grad;
var renderer = frostAuraVFX.GetComponent<ParticleSystemRenderer>();
// Steal material from an existing Valheim effect
GameObject freezingVfx = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("vfx_Freezing");
if (freezingVfx != null)
{
ParticleSystemRenderer origRenderer = freezingVfx.GetComponentInChildren<ParticleSystemRenderer>();
if (origRenderer != null)
{
renderer.material = origRenderer.material;
}
}
}
if (!frostAuraVFX.activeSelf)
{
frostAuraVFX.SetActive(true);
}
}
else
{
if (frostAuraVFX != null && frostAuraVFX.activeSelf)
{
frostAuraVFX.SetActive(false);
}
}
}
private void ApplyColdAura()
{
if (Player.m_localPlayer == null) return;
Vector3 center = Player.m_localPlayer.transform.position;
// Once per tick, not once per enemy - see SkadiMagicSkill.RaiseForAuraTick.
bool burnedSomething = false;
foreach (Character c in Character.GetAllCharacters())
{
if (c == Player.m_localPlayer) continue;
if (c.IsTamed() || c.IsPlayer()) continue;
// Same guard as the Skeleton's fire aura and the Aswid's drain: an always-on aura
// that burns the race's own kin would, with RaceGrudge in place, keep every wolf,
// drake and dverger permanently angry at a Skadi who never attacked anything.
if (!BaseAI.IsEnemy(Player.m_localPlayer, c)) continue;
if (Vector3.Distance(center, c.transform.position) <= SkadiConfig.AuraRadius.Value)
{
HitData hit = new HitData();
hit.m_damage.m_frost = SkadiConfig.AuraDamagePerTick.Value;
hit.m_point = c.transform.position;
hit.m_dir = (c.transform.position - center).normalized;
hit.SetAttacker(Player.m_localPlayer);
c.ApplyDamage(hit, true, false);
burnedSomething = true;
}
}
if (burnedSomething) SkadiMagicSkill.RaiseForAuraTick();
}
private void TryTransformWithRules(SkadiProgression.FormRules rules)
{
if (rules == null || rules.Form == SkadiProgression.FormType.None) return;
if (isTransformed)
{
StartCoroutine(RevertToHumanRoutine());
return;
}
if (rules.CooldownMinutes > 0)
{
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_SkadiCooldown".GetStableHashCode());
if (cdSE != null)
{
float m_time = HarmonyLib.Traverse.Create(cdSE).Field<float>("m_time").Value;
float remaining = cdSE.m_ttl - m_time;
if (remaining < 0) remaining = 0;
int rMin = Mathf.FloorToInt(remaining / 60f);
int rSec = Mathf.FloorToInt(remaining % 60f);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"Dragon Form is on cooldown ({rMin}:{rSec:00}).");
return;
}
}
activeRules = rules;
StartCoroutine(TransformRoutine(rules));
}
private Vector3 GetFormScale(SkadiProgression.FormType form)
{
if (form == SkadiProgression.FormType.Moder) return Vector3.one * SkadiConfig.ModerScale.Value;
if (form == SkadiProgression.FormType.SkeletonDragon) return Vector3.one * SkadiConfig.FaderScale.Value;
return Vector3.one * SkadiConfig.DrakeScale.Value; // Drake
}
private IEnumerator TransformRoutine(SkadiProgression.FormRules rules)
{
isTransformingSequence = true;
ZSyncAnimation zAnim = Player.m_localPlayer.GetComponent<ZSyncAnimation>();
if (zAnim != null)
{
RaceInput.SuppressGuardianPowerBriefly();
zAnim.SetTrigger("gpower");
}
yield return new WaitForSeconds(1.1f);
SpawnPoofEffect();
ExecuteTransformation(rules);
if (currentTransformation != null)
{
float elapsed = 0f;
float duration = 0.5f;
Vector3 endScale = GetFormScale(rules.Form);
Vector3 startScale = endScale * 0.5f;
currentTransformation.transform.localScale = startScale;
while (elapsed < duration)
{
if (currentTransformation == null) break;
currentTransformation.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
if (currentTransformation != null) currentTransformation.transform.localScale = endScale;
}
isTransformingSequence = false;
}
private System.Collections.IEnumerator RevertToHumanRoutine()
{
isTransformingSequence = true;
if (Player.m_localPlayer.GetComponent<ZNetView>() != null) {
Player.m_localPlayer.GetComponent<ZNetView>().GetZDO().Set("Skadi_Form", "");
}
if (currentTransformation != null)
{
DrakeFormBehavior drakeBehavior = currentTransformation.GetComponent<DrakeFormBehavior>();
if (drakeBehavior != null) drakeBehavior.enabled = false;
float elapsed = 0f;
float duration = 0.5f;
Vector3 startScale = currentTransformation.transform.localScale;
float endMultiplier = 0.5f;
Vector3 endScale = startScale * endMultiplier;
while (elapsed < duration)
{
if (currentTransformation == null) break;
currentTransformation.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
}
SpawnPoofEffect();
yield return new WaitForSeconds(0.1f);
ExecuteReversion();
isTransformingSequence = false;
}
private void SpawnPoofEffect()
{
if (Player.m_localPlayer == null) return;
Vector3 pos = Player.m_localPlayer.transform.position + Vector3.up;
GameObject smoke = PrefabManager.Cache.GetPrefab<GameObject>("vfx_corpse_destruction");
if (smoke != null) Instantiate(smoke, pos, Quaternion.identity);
GameObject sparks = PrefabManager.Cache.GetPrefab<GameObject>("vfx_HitSparks");
if (sparks != null) Instantiate(sparks, pos, Quaternion.identity);
}
private void ExecuteTransformation(SkadiProgression.FormRules rules)
{
Transform playerVisual = Player.m_localPlayer.transform.Find("Visual");
string prefabName = "";
switch (rules.Form)
{
case SkadiProgression.FormType.Drake: prefabName = "Hatchling"; break;
case SkadiProgression.FormType.Moder: prefabName = "Dragon"; break;
case SkadiProgression.FormType.SkeletonDragon: prefabName = "Fader"; break;
}
if (Player.m_localPlayer.GetComponent<ZNetView>() != null) {
Player.m_localPlayer.GetComponent<ZNetView>().GetZDO().Set("Skadi_Form", prefabName);
}
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
// Sync to ZDO
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_SkadiForm", prefabName);
}
if (prefab != null && playerVisual != null)
{
PlayerVisualHider.Hide(playerVisual, "skadi-local-form");
Transform visual = prefab.transform.Find("Visual");
if (visual != null)
{
currentTransformation = Instantiate(visual.gameObject, Player.m_localPlayer.transform);
if (prefabName == "Hatchling")
{
currentTransformation.transform.localPosition = new Vector3(0f, -1.0f, 0f);
}
else if (prefabName == "Fader")
{
// Turn Fader into a Frost Skeleton Dragon
foreach (Renderer r in currentTransformation.GetComponentsInChildren<Renderer>())
{
if (r.material != null)
{
r.material.SetColor("_Color", new Color(0.6f, 0.8f, 1f, 1f));
if (r.material.HasProperty("_EmissionColor"))
{
r.material.SetColor("_EmissionColor", new Color(0f, 0.5f, 1f, 1f));
}
}
}
}
else
{
currentTransformation.transform.localPosition = Vector3.zero;
}
currentTransformation.transform.localRotation = Quaternion.identity;
// Keep AnimEvent so native sounds (footsteps, attack shouts) play correctly!
DrakeFormBehavior behavior = currentTransformation.AddComponent<DrakeFormBehavior>();
behavior.Initialize(rules);
if (prefabName == "Hatchling") Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are a Drake!");
else if (prefabName == "Dragon") Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are Moder!");
else if (prefabName == "Fader") Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are Fader!");
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()
{
Transform playerVisual = Player.m_localPlayer.transform.Find("Visual");
if (currentTransformation != null) Destroy(currentTransformation);
// Sync to ZDO
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_SkadiForm", "");
}
var forms1 = Player.m_localPlayer.GetComponentsInChildren<DrakeFormBehavior>(true);
foreach (var f in forms1) Destroy(f.gameObject);
PlayerVisualHider.Show(playerVisual, "skadi-local-revert");
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.");
if (activeRules != null && activeRules.CooldownMinutes > 0)
{
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_SkadiCooldown".GetStableHashCode(), true);
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_SkadiCooldown".GetStableHashCode());
if (cdSE != null) cdSE.m_ttl = activeRules.CooldownMinutes * 60f;
}
activeRules = null;
}
}
}