RacesOfValheim/JotunnModStub/Trenta/TrentaMuspell.cs
kanym 99ec4134be fix(trenta): the Muspell no longer swings the weapon in hand
The Muspell was the one form without the attack blocks every other form
has. Each stomp and spike also started the hidden human's attack, and the
Elder clone's CharacterAnimEvent fired a held bow or crossbow through
OnAttackTrigger, several shots a swing.

StartAttack, PlayerAttackInput and OnAttackTrigger are shut while the
Muspell is up, and the guard is cleared after SetControls, since the
spike sits on Right Mouse, which is also Block.
2026-10-29 01:50:33 +01:00

545 lines
24 KiB
C#

using System.Collections;
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Muspell (Fader): toggle with J into a half-size The Elder and back. Structured as closely
/// as possible on FenrirRace.cs's own transform/revert routines - poof, clone the target's
/// "Visual" child onto the player, shrink the player's own Visual to nothing, drive the clone
/// with its own per-form Animator-reading MonoBehaviour (MuspellFormBehavior, the same shape
/// as FenrirFormBehavior). The permanent-Burning/ignite-attacker fire mechanic was tried and
/// dropped - the flame VFX glitched with no reliable fix in reach, and the player asked for it
/// (and the fire damage that rode along with it) removed rather than chased further.
/// </summary>
public static class TrentaMuspell
{
public static bool IsTransformed { get; private set; }
private static GameObject currentTransformation;
private static bool isTransformingSequence;
/// <summary>
/// How high the form's head sits above the player's feet at a form scale of 1, measured
/// off the clone the moment it is made. Multiplied by the form's current scale it gives the
/// eye height, so the camera rides the grow and shrink tween with the model.
/// </summary>
private static float headHeightAtScaleOne;
/// <summary>
/// The eye height the Muspell wants for <paramref name="player"/>, for RaceEyeHeight.
///
/// The form hides the player's own body by shrinking its Visual to 0.001, and RaceEyeHeight
/// reads anything that small as "hidden" and leaves the eye alone - so the camera stayed at
/// a person's eye level inside something the size of a house. The form is local only, so
/// this only ever answers for the local player.
/// </summary>
public static bool TryGetEyeHeight(Player player, out float height)
{
height = 0f;
if (!IsTransformed || currentTransformation == null || headHeightAtScaleOne <= 0f) return false;
if (player == null || player != Player.m_localPlayer) return false;
height = headHeightAtScaleOne * currentTransformation.transform.localScale.y;
return true;
}
public static void Toggle(Player player)
{
if (isTransformingSequence) return;
if (IsTransformed)
{
formRoutine = TrentaRace.Instance.StartCoroutine(RevertRoutine(player));
}
else
{
formRoutine = TrentaRace.Instance.StartCoroutine(TransformRoutine(player));
}
}
/// <summary>Called from TrentaRace.Update unconditionally, the same way Hornet's Nest is -
/// a race change, a tier drop or death has to end the transformation even though nothing
/// would otherwise be left running to notice.</summary>
public static void ForceRevert(Player player)
{
if (IsTransformed && !isTransformingSequence)
{
formRoutine = TrentaRace.Instance.StartCoroutine(RevertRoutine(player));
}
}
// The one transform or revert routine in flight, if any, so ResetRace can stop it.
private static Coroutine formRoutine;
/// <summary>
/// Drops the Muspell on the spot for ResetRace. ForceRevert would get there too, from
/// TrentaRace.Update, but a frame and a half-second tween later - after ResetRace has
/// already reopened the menu - and not at all if the reset lands mid-gesture.
/// </summary>
/// <returns>True if there was a form to drop.</returns>
public static bool HardResetForReset(Player player)
{
if (player == null) return false;
if (formRoutine != null && TrentaRace.Instance != null)
{
TrentaRace.Instance.StopCoroutine(formRoutine);
}
formRoutine = null;
bool hadForm = IsTransformed || isTransformingSequence || currentTransformation != null;
if (hadForm)
{
if (currentTransformation != null) Object.Destroy(currentTransformation);
currentTransformation = null;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_MuspellForm", false);
Transform playerVisual = player.transform.Find("Visual");
if (playerVisual != null)
{
playerVisual.localScale = Vector3.one;
playerVisual.gameObject.SetActive(true);
}
}
IsTransformed = false;
isTransformingSequence = false;
return hadForm;
}
/// <summary>
/// Called by Purple Rain instead of its usual staff_summon trigger whenever Muspell is
/// active - The Elder's own root-summon gesture, played on the transformation clone's
/// Animator rather than the player's. Returns false (and does nothing) if not transformed,
/// so TryPurpleRain's own fallback to staff_summon still covers the normal case.
/// </summary>
public static bool TryPlayRootSummonAnimation()
{
if (!IsTransformed || currentTransformation == null) return false;
Animator formAnim = currentTransformation.GetComponent<Animator>() ?? currentTransformation.GetComponentInChildren<Animator>();
if (formAnim == null) return false;
try { formAnim.SetTrigger(TrentaConfig.MuspellRootSummonTrigger); } catch { }
return true;
}
private static IEnumerator TransformRoutine(Player player)
{
isTransformingSequence = true;
var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null)
{
// The transformation poof itself, not an ability cast - "gpower" (the arms-raised
// Guardian Power clip, borrowed the same way FenrirRace's own TransformIntoWolfRoutine
// borrows it for its transformation) rather than staff_summon, which is reserved for
// Purple Rain.
RaceInput.SuppressGuardianPowerBriefly();
zanim.SetTrigger("gpower");
}
yield return new WaitForSeconds(1.1f);
SpawnPoofEffect(player);
yield return new WaitForSeconds(0.1f);
ExecuteTransformation(player);
// Grows in from small rather than popping straight to 50%, the same tween
// FenrirRace uses for its own non-wolf forms.
float elapsed = 0f;
float duration = 0.5f;
Vector3 startScale = Vector3.one * (TrentaConfig.MuspellScale * 0.2f);
Vector3 endScale = Vector3.one * TrentaConfig.MuspellScale;
if (currentTransformation != null) 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 static IEnumerator RevertRoutine(Player player)
{
isTransformingSequence = true;
if (currentTransformation != null)
{
MuspellFormBehavior behavior = currentTransformation.GetComponent<MuspellFormBehavior>();
if (behavior != null) behavior.enabled = false;
float elapsed = 0f;
float duration = 0.5f;
Vector3 startScale = currentTransformation.transform.localScale;
Vector3 endScale = Vector3.one * (TrentaConfig.MuspellScale * 0.2f);
while (elapsed < duration)
{
if (currentTransformation == null) break;
currentTransformation.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
}
SpawnPoofEffect(player);
yield return new WaitForSeconds(0.1f);
ExecuteReversion(player);
isTransformingSequence = false;
}
private static void SpawnPoofEffect(Player player)
{
if (player == null) return;
Vector3 pos = player.transform.position + Vector3.up;
// _large rather than the _medium the other two forms use: the Muspell is the biggest
// thing this mod turns a player into, and a body-sized puff does not cover it. A bare
// "vfx_corpse_destruction" is not a prefab in this game, so until now the Muspell was
// the one transformation with no covering effect of any kind - Fenrir and Skadi at least
// had their sparks.
GameObject smoke = PrefabManager.Cache.GetPrefab<GameObject>("vfx_corpse_destruction_large");
if (smoke != null) Object.Instantiate(smoke, pos, Quaternion.identity);
}
private static void ExecuteTransformation(Player player)
{
Transform playerVisual = player.transform.Find("Visual");
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(TrentaConfig.MuspellFormPrefab);
if (prefab == null || playerVisual == null)
{
Jotunn.Logger.LogWarning($"[Trenta] Muspell: could not find form prefab '{TrentaConfig.MuspellFormPrefab}'.");
return;
}
playerVisual.localScale = Vector3.one * 0.001f;
Transform visual = prefab.transform.Find("Visual") ?? prefab.transform;
currentTransformation = Object.Instantiate(visual.gameObject, player.transform);
currentTransformation.transform.localPosition = Vector3.zero;
currentTransformation.transform.localRotation = Quaternion.identity;
// Measured here, straight off the clone, before the grow tween touches its scale. The
// head is the same bone the spike volley fires from.
Transform head = currentTransformation.transform.Find(MuspellFormBehavior.HeadPath);
float cloneScale = currentTransformation.transform.localScale.y;
headHeightAtScaleOne = head != null && cloneScale > 0f
? (head.position.y - player.transform.position.y) / cloneScale
: 0f;
// Same reasoning as FenrirRace.ExecuteTransformation: the clone must never carry
// whatever AI/gameplay component made the source a functioning boss.
Component animEvent = currentTransformation.GetComponent("AnimEvent");
if (animEvent != null) Object.Destroy(animEvent);
foreach (Component ai in currentTransformation.GetComponentsInChildren<BaseAI>(true)) Object.Destroy(ai);
foreach (Component character in currentTransformation.GetComponentsInChildren<Character>(true)) Object.Destroy(character);
foreach (Component znet in currentTransformation.GetComponentsInChildren<ZNetView>(true)) Object.Destroy(znet);
currentTransformation.AddComponent<MuspellFormBehavior>();
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_MuspellForm", true);
}
IsTransformed = true;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_are_muspell_ash_ember_given"));
}
private static void ExecuteReversion(Player player)
{
Transform playerVisual = player.transform.Find("Visual");
if (currentTransformation != null) Object.Destroy(currentTransformation);
currentTransformation = null;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_MuspellForm", false);
}
if (playerVisual != null)
{
playerVisual.localScale = Vector3.one;
playerVisual.gameObject.SetActive(true);
}
IsTransformed = false;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_return_rooted_form"));
}
}
/// <summary>
/// Drives the transformation clone's Animator and its two mouse-button attacks - the same
/// shape as FenrirBehaviors.cs's per-form classes (locomotion sync from the player's own
/// Animator when idle, lock-and-trigger-and-damage coroutines per attack).
/// </summary>
public class MuspellFormBehavior : MonoBehaviour
{
public const string HeadPath = "Armature/root/spine1/spine2/spine3/head";
private Animator playerAnim;
private Animator formAnim;
private Transform muzzle;
private bool isAttacking;
private void Start()
{
playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent<Animator>();
formAnim = GetComponent<Animator>();
if (formAnim == null) formAnim = GetComponentInChildren<Animator>();
// The spike volley should leave from the Elder's own mouth, not the (now hidden)
// player's eye point underneath it.
muzzle = transform.Find(HeadPath);
}
private void Update()
{
if (playerAnim == null || formAnim == null || Player.m_localPlayer == null) return;
if (isAttacking) return;
bool isGrounded = playerAnim.GetBool("onGround");
TrySet(() => formAnim.SetBool("onGround", isGrounded));
TrySet(() => formAnim.SetBool("inWater", playerAnim.GetBool("inWater")));
if (!isGrounded || Player.m_localPlayer.IsCrouching())
{
TrySet(() => formAnim.SetFloat("forward_speed", 0f));
TrySet(() => formAnim.SetFloat("sideway_speed", 0f));
}
else
{
TrySet(() => formAnim.SetFloat("forward_speed", playerAnim.GetFloat("forward_speed")));
TrySet(() => formAnim.SetFloat("sideway_speed", playerAnim.GetFloat("sideway_speed")));
}
LoopIdle();
if (!isGrounded || !RaceInput.Allowed) return;
if (RaceInput.AttackDown(0)) // Stomp
{
StartCoroutine(StompRoutine());
}
else if (RaceInput.AttackDown(1)) // Spike volley
{
StartCoroutine(SpikeRoutine());
}
}
private const string IdleClip = "Unarmed Idle";
/// <summary>
/// Keeps the idle going. The Elder's "Unarmed Idle" clip is not a looping clip (dumpanim:
/// loop=False, 1.90s), so after the stand-up or any attack the form played it once and
/// froze on its last frame. The boss never showed it, being hardly ever idle; a player in
/// the form is idle most of the time. The clip's flag lives in the game's asset, so the
/// state is restarted from here instead, once it has run to its end.
///
/// The idle shares a locomotion blend tree with the four Swagger Walk clips, so the clip
/// list for the state holds all of them and the idle is not necessarily first: it is found
/// by name and must be carrying most of the weight, which is what "standing still" means.
/// Play and not CrossFade: Unity can ignore a cross-fade from a state into itself, and
/// the first version of this did exactly nothing for that reason.
/// </summary>
private void LoopIdle()
{
if (formAnim.IsInTransition(0)) return;
bool idle = false;
foreach (AnimatorClipInfo info in formAnim.GetCurrentAnimatorClipInfo(0))
{
if (info.clip != null && info.clip.name == IdleClip && info.weight >= 0.5f)
{
idle = true;
break;
}
}
if (!idle) return;
AnimatorStateInfo state = formAnim.GetCurrentAnimatorStateInfo(0);
if (state.normalizedTime < 1f) return;
formAnim.Play(state.fullPathHash, 0, 0f);
}
private static void TrySet(System.Action set)
{
try { set(); } catch { }
}
private IEnumerator StompRoutine()
{
isAttacking = true;
TrySet(() => formAnim.SetFloat("forward_speed", 0f));
TrySet(() => formAnim.SetFloat("sideway_speed", 0f));
// gd_king_stomp's own attack has m_attackRandomAnimations=2 - The Elder itself picks
// between "stomp0"/"stomp1" at random each swing, so this mirrors that instead of
// always firing the same one.
string trigger = TrentaConfig.MuspellStompTrigger + Random.Range(0, TrentaConfig.MuspellStompTriggerVariants);
TrySet(() => formAnim.SetTrigger(trigger));
yield return new WaitForSeconds(0.5f);
ExecuteMeleeDamage(TrentaConfig.MuspellStompDamage, TrentaConfig.MuspellStompRadius);
yield return new WaitForSeconds(0.5f);
TrySet(() => formAnim.ResetTrigger(trigger));
isAttacking = false;
}
private IEnumerator SpikeRoutine()
{
isAttacking = true;
TrySet(() => formAnim.SetFloat("forward_speed", 0f));
TrySet(() => formAnim.SetFloat("sideway_speed", 0f));
TrySet(() => formAnim.SetTrigger(TrentaConfig.MuspellSpikeTrigger));
yield return new WaitForSeconds(0.4f);
FireSpikeProjectile();
yield return new WaitForSeconds(0.6f);
TrySet(() => formAnim.ResetTrigger(TrentaConfig.MuspellSpikeTrigger));
isAttacking = false;
}
/// <summary>Close-range, all-around - matches Stomp being an area slam rather than a
/// directional swing.</summary>
private void ExecuteMeleeDamage(float baseDamage, float radius)
{
Player player = Player.m_localPlayer;
if (player == null) return;
Vector3 center = player.transform.position + Vector3.up;
float unarmedSkillLevel = player.GetSkillLevel(Skills.SkillType.Unarmed);
float totalDamage = baseDamage + unarmedSkillLevel;
HashSet<GameObject> hit = new HashSet<GameObject>();
foreach (Collider collider in Physics.OverlapSphere(center, radius))
{
Character target = collider.GetComponentInParent<Character>();
if (target == null || target == player || target.IsDead() || !hit.Add(target.gameObject)) continue;
if (!BaseAI.IsEnemy(player, target)) continue;
DealDamage(player, target, totalDamage, HitData.DamageType.Blunt, Vector3.zero);
}
}
/// <summary>
/// The real ranged attack - "gdking_root_projectile", the same one gd_king_shoot fires -
/// rather than an instant hitscan, so it travels, can be dodged and can miss the same way
/// the boss's own volley does. Spawn/Setup shape copied from TrolRace's own rock throw,
/// the established pattern for a custom projectile in this codebase.
/// </summary>
private void FireSpikeProjectile()
{
Player player = Player.m_localPlayer;
if (player == null) return;
GameObject projPrefab = ZNetScene.instance.GetPrefab(TrentaConfig.MuspellSpikeProjectilePrefab);
if (projPrefab == null)
{
Jotunn.Logger.LogWarning($"[Trenta] Muspell: could not find projectile prefab '{TrentaConfig.MuspellSpikeProjectilePrefab}'.");
return;
}
// Aim still follows the player's own look direction (mouse/camera), only the spawn
// point moves to the Elder clone's mouth so the shot visibly comes from the model
// that's on screen instead of the hidden player underneath it.
Vector3 origin = muzzle != null ? muzzle.position : player.GetEyePoint();
Vector3 spawnPos = origin + player.GetLookDir() * 1.5f;
GameObject projInstance = Object.Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(player.GetLookDir()));
Projectile proj = projInstance.GetComponent<Projectile>();
if (proj == null) return;
float unarmedSkillLevel = player.GetSkillLevel(Skills.SkillType.Unarmed);
HitData hitData = new HitData();
hitData.m_damage.m_pierce = TrentaConfig.MuspellSpikeDamage + unarmedSkillLevel;
hitData.m_skill = Skills.SkillType.Unarmed;
hitData.SetAttacker(player);
proj.Setup(player, player.GetLookDir() * TrentaConfig.MuspellSpikeVelocity, -1f, hitData, null, null);
}
private void DealDamage(Player attacker, Character target, float amount, HitData.DamageType type, Vector3 dir)
{
HitData hitData = new HitData();
if (type == HitData.DamageType.Pierce) hitData.m_damage.m_pierce = amount;
else hitData.m_damage.m_blunt = amount;
hitData.m_point = target.GetCenterPoint();
hitData.m_dir = dir;
hitData.m_skill = Skills.SkillType.Unarmed;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.SetAttacker(attacker);
target.Damage(hitData);
}
}
/// <summary>
/// The hidden human does not fight under the Muspell. Every other form already had these
/// (see Fenrir's BlockPlayerLogicAttackPatch); the Muspell had none, so each stomp and spike
/// also swung the weapon in hand, and the Elder clone's own CharacterAnimEvent fired the held
/// bow or crossbow through OnAttackTrigger on top of that: a tester's bow shot several times a
/// swing. Right Mouse is the spike and the Block button at once, so the guard is cleared too,
/// as BlockPlayerGuardPatch does it.
/// </summary>
internal static class TrentaMuspellAttackBlock
{
private static bool LocalInForm(Character character) =>
TrentaMuspell.IsTransformed && character != null && character == Player.m_localPlayer;
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.StartAttack))]
public static class Trenta_MuspellBlockNativeAttack_Patch
{
public static bool Prefix(Humanoid __instance) => !LocalInForm(__instance);
}
[HarmonyPatch(typeof(Player), "PlayerAttackInput")]
public static class Trenta_MuspellBlockAttackInput_Patch
{
public static bool Prefix(Player __instance) => !LocalInForm(__instance);
}
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))]
public static class Trenta_MuspellBlockAttackTrigger_Patch
{
public static bool Prefix(Humanoid __instance) => !LocalInForm(__instance);
}
[HarmonyPatch(typeof(Player), nameof(Player.SetControls))]
public static class Trenta_MuspellBlockGuard_Patch
{
private static readonly AccessTools.FieldRef<Character, bool> Blocking =
AccessTools.FieldRefAccess<Character, bool>("m_blocking");
public static void Postfix(Player __instance)
{
if (LocalInForm(__instance)) Blocking(__instance) = false;
}
}
}
}