RacesOfValheim/JotunnModStub/Sverm/SvermRavagerForm.cs
kanym 63e252d9e9 feat(sverm): the Ravager's ram lunges with the clip's root motion
Vanilla only takes root motion during a native attack, which this form never
starts, so a relay on the costume's Animator collects it and a prefix on
Character.ApplyRootMotion applies it to the player the same way (x55).
2026-10-17 20:24:43 +02:00

1073 lines
51 KiB
C#

using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Ravager Strain: from Yagluth on, a Sverm can become a Seeker Brute for two minutes.
///
/// Replaces the earlier Stinger Morph (a Deathsquito flight form). Players found that form's
/// glass-cannon shape too strong for what it cost, so this is the opposite trade: no flight,
/// no summons, and the carapace is worth twice as much for as long as the form holds - the
/// carapace itself is never removed. Same duration, same cooldown as the form it replaces;
/// only the shape of the trade changed.
///
/// COMBAT FOLLOWS FENRIR AND SKADI'S OWN PATTERN, not Valheim's weapon system. Nothing gets
/// equipped. Humanoid.StartAttack is blocked outright for as long as the form is up, and
/// RavagerFormBehavior runs its own attack coroutines instead - a trigger on the model's
/// Animator, a timed Physics.OverlapSphere, real damage numbers borrowed from
/// SvermRavagerAttacks. The earlier version tried to clone the Brute's own weapons and let
/// them run through Valheim's real Attack.Start, and it never stopped fighting the game:
/// GetCurrentBlocker turning right-click into a parry, player.InAttack() ending before the
/// visible clip did, wiring a working secondary attack by hand. Left click bites, right click
/// rams, middle click slams, G roars - a short-cooldown AoE around the player rather than a
/// fourth forward swing, since the Brute's own taunt was never a hit in the first place.
/// </summary>
public static class SvermRavagerForm
{
public static bool IsActive { get; private set; }
/// <summary>True while the local Brute is inside a swing or the roar.
/// Sverm_RavagerHoldStill_Patch holds the player still for exactly that long.</summary>
public static bool LocalAttacking { get; set; }
// Read by Sverm_RavagerRemoteVisuals_Patch (SvermPatches.cs) so every other client can
// tell the form is up at all - without this the whole thing was local-only, exactly like
// DrakeFormBehavior's flight flag and Fenrir's own form key, and other players saw nothing
// but a Sverm standing still for the whole two minutes.
public const string ActiveKey = "RacesOfValheim_SvermRavagerForm";
// Same running-count trick as DrakeFormBehavior.AttackTriggerKey: the trigger name alone
// cannot tell a remote client "a new bite just happened" when the same trigger fires twice
// in a row, since an unchanged ZDO string never re-fires a Unity Animator trigger.
public const string AttackTriggerKey = "RacesOfValheim_SvermRavagerAttack";
private static int attackTriggerSeq = 0;
private static GameObject model;
private static float expiresAt;
private static float nextAllowedAt;
// Guards the ~1.1s "gpower" gesture in EnterRoutine, and separately the shrink in
// ExitRoutine: without them, a second key press mid-gesture would start a second routine
// on top of the first, the same double-transform bug Aswid's own isTransformingSequence
// flag exists to prevent.
private static bool transforming;
private static bool exiting;
private static GameObject template;
private static bool templateBuildAttempted;
// ─── The template ───────────────────────────────────────────────────
/// <summary>
/// Strips the Seeker Brute's borrowed model down to a costume, once, from a moment where
/// that is safe to do - the same rule ModelBorrow exists to enforce, and the same one
/// WarVultureVisual.BuildTemplate follows for its own borrowed bird. Call it from a
/// CreateAllModAssets-time hook; it no-ops on every call after the first.
///
/// FOUND IN PLAY: the old code instantiated the source's Animator sub-object directly at
/// Enter() time, mid-gameplay, and never stripped it. The Brute's own footstep-effect
/// script came along for the ride, alive, and spent every frame of the form logging
/// "FAiled to find foot:l.backfoot" because the bones it wanted only exist on the
/// source's own untouched rig - along with whatever else survived (Character, MonsterAI,
/// a Rigidbody, a ZNetView) that this class never meant to carry.
///
/// DestroyImmediate only, and only because the holder is inactive before the Instantiate
/// below: an active clone would Awake every one of those scripts for a frame before the
/// strip could remove them, which is the exact bug ModelBorrow's own docstring names.
/// Object.Destroy (deferred) would not be safe here for the same reason - by the time it
/// actually runs, the frame that mattered has already passed.
/// </summary>
public static void BuildTemplate()
{
if (template != null || templateBuildAttempted) return;
templateBuildAttempted = true;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SvermConfig.RavagerCreature);
GameObject animated = source != null ? source.GetComponentInChildren<Animator>()?.gameObject : null;
if (animated == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{SvermConfig.RavagerCreature}' model to build the " +
"Ravager Strain template from; the form will run without a body.");
return;
}
GameObject holder = new GameObject("SvermRavagerTemplate");
Object.DontDestroyOnLoad(holder);
holder.SetActive(false); // BEFORE Instantiate: nothing on the copy gets to Awake.
GameObject copy = Object.Instantiate(animated, holder.transform);
copy.name = "model";
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.transform.localScale = animated.transform.localScale;
// Everything that is not a Renderer or a Transform. Animator is a Behaviour, not a
// MonoBehaviour, so it is never touched by the first loop and survives on purpose -
// it is the one live thing this costume is allowed to keep.
// Dependents first: a single pass left the Brute's Humanoid on the costume, because
// CharacterDrop requires it and came later. See ModelBorrow.StripBehaviours.
ModelBorrow.StripBehaviours(copy, "Sverm");
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true))
{
if (collider != null) Object.DestroyImmediate(collider);
}
foreach (Rigidbody body in copy.GetComponentsInChildren<Rigidbody>(true))
{
if (body != null) Object.DestroyImmediate(body);
}
foreach (ZNetView nview in copy.GetComponentsInChildren<ZNetView>(true))
{
if (nview != null) Object.DestroyImmediate(nview);
}
template = copy;
Jotunn.Logger.LogInfo($"[Sverm] Ravager Strain template built from '{SvermConfig.RavagerCreature}'.");
}
// ─── Driver ──────────────────────────────────────────────────────────
public static void Tick(Player player)
{
if (player == null || player != Player.m_localPlayer)
{
return;
}
// While the entry gesture (EnterRoutine) or the exit shrink (ExitRoutine) is still
// playing, nothing below should react to a key press or a death mid-sequence.
if (transforming || exiting) return;
// Death ends it immediately, and so does ceasing to be a Sverm. Both leave a body
// hidden and a bug that is very hard to read, so they are checked before anything
// else - and neither one gets the graceful shrink, on purpose: a corpse or a race
// change is not the moment for a half-second animation, it is the moment to clean up.
if (IsActive && (player.IsDead() || !SvermVisuals.IsSvermPlayer(player)))
{
Exit(player, spendCooldown: false);
return;
}
if (IsActive && Time.time >= expiresAt)
{
RunExit(player, spendCooldown: true, "$rov_msg_sverm_shell_recedes");
return;
}
// No manual cancel: the form is short (two minutes) on purpose, and letting G end it
// early meant a stray press mid-fight burned the whole cooldown for a form that had
// barely started. While IsActive, the key does nothing at all - the timer is the only
// way out, same as death or losing the race.
if (IsActive) return;
if (!SvermConfigManagement.RavagerKey.Value.IsDown() &&
!RaceInput.ConsumePress(SvermConfigManagement.RavagerKey.Value)) return;
if (!SvermVisuals.IsSvermPlayer(player)) return;
if (!SvermProgression.Current.RavagerForm)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_strain_has_not_taken_yet"));
return;
}
if (Time.time < nextAllowedAt)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_strain_spent"));
return;
}
if (SvermRace.Instance != null)
{
formRoutine = SvermRace.Instance.StartCoroutine(EnterRoutine(player));
}
else
{
// No host to run the gesture on - a state that should not happen outside a very
// early loading frame, but the form working ungestured beats it not working at
// all.
Enter(player);
}
}
/// <summary>
/// The transformation's own animation: the same "gpower" arms-raised gesture Aswid,
/// Skadi and Fenrir all borrow for their own transformations (RaceInput's own comment
/// names all three), suppressed so it never fires the player's real Guardian Power. The
/// actual state change - IsActive, the weapons, the hidden body, the worn model - waits
/// out the gesture first, the same order TransformIntoBatRoutine uses in AswidRace.cs.
/// </summary>
private static System.Collections.IEnumerator EnterRoutine(Player player)
{
transforming = true;
ZSyncAnimation zAnim = player.GetComponent<ZSyncAnimation>();
if (zAnim != null)
{
RaceInput.SuppressGuardianPowerBriefly();
zAnim.SetTrigger("gpower");
}
yield return new WaitForSeconds(1.1f);
// The gesture takes over a second; a lot can happen to the player in that window.
if (player == null || player != Player.m_localPlayer || player.IsDead() || !SvermVisuals.IsSvermPlayer(player))
{
transforming = false;
yield break;
}
Enter(player);
transforming = false;
}
// ─── Enter and leave ─────────────────────────────────────────────────
private static void Enter(Player player)
{
IsActive = true;
expiresAt = Time.time + SvermConfig.RavagerDurationSeconds;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set(ActiveKey, true);
player.GetSEMan().AddStatusEffect(SvermConfig.RavagerSE.GetStableHashCode(), true);
Transform visual = player.transform.Find("Visual");
PlayerVisualHider.Hide(visual, "sverm-ravager");
// BuildTemplate is NOT called from here. Enter() runs from Tick(), inside Update, and
// the strip needs DestroyImmediate on an inactive object - safe only from the
// CreateAllModAssets-time hook that actually builds this. If that hook never ran, the
// template stays null and the form falls back to a bare body below rather than
// risking an unsafe strip mid-gameplay.
if (template != null)
{
// A plain Instantiate of an already-stripped template - safe in this context
// (mid-gameplay, inside Update) precisely because nothing left on it can Awake
// into anything. See BuildTemplate for why that matters.
model = Object.Instantiate(template, player.transform.position, player.transform.rotation, player.transform);
model.transform.localPosition = Vector3.zero;
// SCALE COMES FROM THE SOURCE, not from 1 - same reasoning as the old Stinger
// Morph. The multiplier defaults to 1 (the Brute's own authored size, full bulk,
// by design) and is only there for an eye to correct it against.
Vector3 fullScale = template.transform.localScale * SvermConfigManagement.RavagerScale;
// Grows in rather than popping to full size at once, starting at half scale and
// reaching full over half a second - the entrance the transformation itself was
// missing. ScaleTween owns the model reference for that half second, not Enter,
// so nothing here needs to wait on it.
model.transform.localScale = fullScale * 0.5f;
if (SvermRace.Instance != null)
{
SvermRace.Instance.StartCoroutine(ScaleTween(model, fullScale * 0.5f, fullScale, 0.5f));
}
else
{
model.transform.localScale = fullScale;
}
// Which way the model faces is a thing only an eye can settle, so it is a config
// value and not a constant - same as the old form.
model.transform.localRotation = Quaternion.Euler(0f, SvermConfigManagement.RavagerYaw, 0f);
model.AddComponent<RavagerFormBehavior>();
}
else
{
// No model is survivable - the carapace and the armour buff still apply - but it
// is worth saying out loud rather than leaving someone to wonder why they turned
// into nothing.
GameObject bare = new GameObject("SvermRavagerBody");
bare.transform.SetParent(player.transform, false);
bare.AddComponent<RavagerFormBehavior>();
model = bare;
}
PlayEffect(SvermConfig.RavagerMorphInEffects, player.transform.position);
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_ravager_strain_takes_hold"));
}
private static void PlayEffect(string[] candidates, Vector3 where)
{
foreach (string name in candidates)
{
GameObject fx = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (fx == null) continue;
Object.Instantiate(fx, where, Quaternion.identity);
return;
}
}
private static void Exit(Player player, bool spendCooldown)
{
IsActive = false;
LocalAttacking = false;
ZNetView exitNview = player.GetComponent<ZNetView>();
if (exitNview != null && exitNview.IsValid()) exitNview.GetZDO().Set(ActiveKey, false);
PlayEffect(SvermConfig.RavagerMorphOutEffects, player.transform.position);
// Nothing was ever equipped for this form - see the class doc for why - so there is
// nothing to hand back here. SvermClawSlot's own throttled pass (Sverm_PlayerUpdate_Patch)
// keeps the claws maintained regardless of Ravager Strain, on its own schedule.
if (model != null)
{
// FOUND IN PLAY: Object.Destroy is deferred to the end of the frame, so
// RavagerFormBehavior's own LateUpdate - the one that re-hides the player's
// Visual every frame to kill the equipment-swap flicker - was still firing AFTER
// Show() ran a few lines below, undoing it the instant it happened. Nothing called
// Show() again afterward, so the player (and whatever VisEquipment had just
// rebuilt while unequipping the Ravager weapon above - the carapace included)
// stayed hidden for good. SetActive(false) makes Unity skip every further
// Update/LateUpdate on this GameObject for the rest of the frame even though the
// object itself is not gone yet, which is the only part of "destroyed" that
// actually matters here.
model.SetActive(false);
Object.Destroy(model);
model = null;
}
player.GetSEMan().RemoveStatusEffect(SvermConfig.RavagerSE.GetStableHashCode());
Transform visual = player.transform.Find("Visual");
PlayerVisualHider.Show(visual, "sverm-ravager-revert");
if (spendCooldown)
{
nextAllowedAt = Time.time + SvermConfig.RavagerCooldownSeconds;
player.GetSEMan().AddStatusEffect(SvermConfig.RavagerCdSE.GetStableHashCode(), true);
}
}
// The enter or exit routine in flight, if any, so ResetRace can stop it. An ExitRoutine
// left running finishes with Exit(spendCooldown: true), which puts the cooldown back on
// after the reset has swept it.
private static Coroutine formRoutine;
/// <summary>
/// Drops Ravager Strain on the spot for ResetRace, and forgets its cooldown: nextAllowedAt
/// is a static the status effect sweep never touches, so without this a player who left
/// the Sverm and came back stayed locked out of the form with no timer in the HUD.
/// </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 && SvermRace.Instance != null)
{
SvermRace.Instance.StopCoroutine(formRoutine);
}
formRoutine = null;
bool hadForm = IsActive || transforming || exiting || model != null;
if (IsActive || model != null) Exit(player, spendCooldown: false);
transforming = false;
exiting = false;
nextAllowedAt = 0f;
return hadForm;
}
/// <summary>Kicks off the graceful exit (shrink, then Exit) if there is a host to run it on.</summary>
private static void RunExit(Player player, bool spendCooldown, string message)
{
if (SvermRace.Instance != null)
{
formRoutine = SvermRace.Instance.StartCoroutine(ExitRoutine(player, spendCooldown, message));
}
else
{
Exit(player, spendCooldown);
if (message != null) player.Message(MessageHud.MessageType.Center, message);
}
}
/// <summary>
/// The mirror of EnterRoutine's grow-in: the model shrinks to half its current scale over
/// half a second before Exit() actually tears anything down, so the form has a send-off
/// instead of a hard cut. Used for the two GRACEFUL exits only (timeout, manual toggle) -
/// death and a race change go through Exit() directly, immediately, on purpose.
/// </summary>
private static System.Collections.IEnumerator ExitRoutine(Player player, bool spendCooldown, string message)
{
exiting = true;
if (model != null)
{
Vector3 current = model.transform.localScale;
yield return ScaleTween(model, current, current * 0.5f, 0.5f);
}
Exit(player, spendCooldown);
if (message != null) player.Message(MessageHud.MessageType.Center, message);
exiting = false;
}
/// <summary>
/// Linear scale from <paramref name="from"/> to <paramref name="to"/> over
/// <paramref name="duration"/> seconds. Bails cleanly if the target disappears mid-tween
/// rather than assuming it cannot - Exit() is free to destroy the model while this is
/// still yielding.
/// </summary>
private static System.Collections.IEnumerator ScaleTween(GameObject target, Vector3 from, Vector3 to, float duration)
{
if (target == null) yield break;
float elapsed = 0f;
while (elapsed < duration)
{
if (target == null) yield break;
elapsed += Time.deltaTime;
target.transform.localScale = Vector3.Lerp(from, to, elapsed / duration);
yield return null;
}
if (target != null) target.transform.localScale = to;
}
// ─── Remote observers ───────────────────────────────────────────────
/// <summary>
/// Builds the same costume Enter() does, minus the grow-in tween (a remote observer just
/// needs the steady-state model, not the entrance) and minus RavagerFormBehavior, which is
/// built around Player.m_localPlayer and would do nothing useful on a copy driven by
/// someone else's client. Sverm_RavagerRemoteVisuals_Patch adds RemoteRavagerAnimator
/// instead, the same way Skadi_MultiplayerVisuals_Patch adds RemoteSkadiAnimator.
/// </summary>
public static GameObject SpawnRemoteModel(Transform playerTransform)
{
if (template == null) return null;
GameObject model = Object.Instantiate(template, playerTransform.position, playerTransform.rotation, playerTransform);
model.transform.localPosition = Vector3.zero;
model.transform.localScale = template.transform.localScale * SvermConfigManagement.RavagerScale;
model.transform.localRotation = Quaternion.Euler(0f, SvermConfigManagement.RavagerYaw, 0f);
return model;
}
/// <summary>
/// Called by RavagerFormBehavior right after it fires a trigger on the local player's own
/// copy of the Animator, so RemoteRavagerAnimator can replay the same clip on every other
/// client. See AttackTriggerKey for why a sequence number rides along with the name.
/// </summary>
public static void PublishAttackTrigger(Player player, string trigger)
{
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
attackTriggerSeq++;
nview.GetZDO().Set(AttackTriggerKey, trigger + "#" + attackTriggerSeq);
}
// ─── The three attacks ───────────────────────────────────────────────
/// <summary>
/// Blocks Valheim's own attack system outright for the whole form, the same way
/// SkadiAttackPatch blocks it for the dragon forms. Whatever the player happens to have
/// equipped never swings and never deals damage while this is up; RavagerFormBehavior's
/// own coroutines are the only thing that can land a hit.
/// </summary>
/// <summary>
/// Holds the Brute still through its attack clips, the way Fenrir_FormHoldStill_Patch and
/// Trol_TrueFormHoldStill_Patch do for their forms. The hidden player kept walking under the
/// costume, so a bite or a slam slid toward whatever WASD held.
/// </summary>
[HarmonyPatch(typeof(Player), "SetControls")]
public static class Sverm_RavagerHoldStill_Patch
{
public static void Prefix(Player __instance, ref Vector3 __0, ref bool jump, ref bool crouch, ref bool dodge)
{
if (__instance != Player.m_localPlayer || !LocalAttacking) return;
if (!IsActive)
{
LocalAttacking = false;
return;
}
__0 = Vector3.zero;
jump = false;
crouch = false;
dodge = false;
}
}
/// <summary>The ram clip's own forward motion, collected by RavagerRootMotionRelay and
/// spent by Sverm_RavagerRootMotion_Patch.</summary>
public static Vector3 PendingRootMotion;
/// <summary>
/// Moves the player by the ram clip's root motion, the way vanilla moves a charging Brute.
/// Vanilla's own path (CharacterAnimEvent.OnAnimatorMove into Character.AddRootMotion) only
/// takes motion while Character.InAttack(), and this form never starts a native attack, so
/// the motion comes in here instead and is applied exactly as Character.ApplyRootMotion
/// applies it: delta times 55, used when it is faster than the walk velocity.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyRootMotion")]
public static class Sverm_RavagerRootMotion_Patch
{
public static void Prefix(Character __instance, ref Vector3 vel)
{
if (__instance != Player.m_localPlayer) return;
Vector3 motion = PendingRootMotion;
PendingRootMotion = Vector3.zero;
if (!IsActive || !LocalAttacking) return;
Vector3 push = motion * 55f;
push.y = 0f;
if (push.magnitude > new Vector3(vel.x, 0f, vel.z).magnitude)
{
vel = new Vector3(push.x, vel.y, push.z);
}
}
}
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Sverm_RavagerBlockNativeAttack_Patch
{
public static bool Prefix(Humanoid __instance)
{
if (__instance != Player.m_localPlayer) return true;
return !IsActive;
}
}
/// <summary>
/// The rest of the human's attack loop - crossbow reload and draw, and the animation event that
/// fires a held attack - shut for the form too. See Fenrir's BlockPlayerAttackInputPatch.
/// </summary>
[HarmonyPatch(typeof(Player), "PlayerAttackInput")]
public static class Sverm_RavagerBlockAttackInput_Patch
{
public static bool Prefix(Player __instance)
{
if (__instance != Player.m_localPlayer) return true;
return !IsActive;
}
}
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))]
public static class Sverm_RavagerBlockAttackTrigger_Patch
{
public static bool Prefix(Humanoid __instance)
{
if (__instance != Player.m_localPlayer) return true;
return !IsActive;
}
}
/// <summary>No food, no mead, no potions. The form is meant to be survived, not sustained.</summary>
[HarmonyPatch(typeof(Humanoid), "UseItem")]
public static class Sverm_RavagerUseItem_Patch
{
public static bool Prefix(Humanoid __instance)
{
if (!IsActive) return true;
return !(__instance is Player player) || player != Player.m_localPlayer;
}
}
}
/// <summary>
/// Sits on the costume's Animator object. Unity calls OnAnimatorMove there instead of moving
/// the costume itself; while Active (the ram), the clip's motion is handed to the player
/// through SvermRavagerForm.PendingRootMotion. Otherwise it is dropped, so the costume stays
/// where the player is.
/// </summary>
public class RavagerRootMotionRelay : MonoBehaviour
{
public Animator Animator;
public bool Active;
private void OnAnimatorMove()
{
if (Active && Animator != null) SvermRavagerForm.PendingRootMotion += Animator.deltaPosition;
}
}
/// <summary>
/// Locomotion AND combat, both held on every frame while the form is up - built on the same
/// method FenrirFormBehavior and DrakeFormBehavior already use for their own transformations,
/// not on Valheim's weapon system. See SvermRavagerAttacks for why.
///
/// UNLIKE THE OLD STINGER MORPH, this never touches m_debugFly - the whole point of Ravager
/// Strain is that it stays on the ground. The player moves exactly as they always do; this
/// component only feeds the worn model's own Animator whatever standard Valheim monster
/// parameters it actually has - forward_speed and onGround, the same pair DrakeFormBehavior
/// drives - plus a jump cue IF the Brute's controller turns out to carry one, checked once at
/// Start rather than assumed. Every SetFloat/SetBool/SetTrigger is guarded by that check, the
/// same pattern WarVultureVisual.Has uses: driving a parameter name the controller does not
/// have is a silent no-op in Unity, but the guard is what makes "does it have one" an answer
/// this logs instead of a guess nobody can see.
/// </summary>
public class RavagerFormBehavior : MonoBehaviour
{
private Animator anim;
private bool hasForwardSpeed;
private bool hasOnGround;
private bool hasJumpTrigger;
private bool hasJumpBool;
private bool wasGrounded = true;
// While true, Update skips both the locomotion sync and any new attack input - the same
// gate FenrirFormBehavior's own isAttacking flag uses, and the direct answer to "the
// animation has to finish before the Brute can move": nothing here can start moving the
// model again, or start a second attack, until the coroutine below clears it.
private bool isAttacking { get => attacking; set { attacking = value; SvermRavagerForm.LocalAttacking = value; } }
private bool attacking;
// The taunt's own cooldown - short, and tracked separately from the other three, which
// have no cooldown of their own beyond their own lock duration.
private float nextTauntAt;
// Every distinct trigger name that has been checked against this Animator and found
// present, so PlayAttack does not pass a name to SetTrigger the controller cannot use.
private readonly System.Collections.Generic.HashSet<string> knownTriggers = new System.Collections.Generic.HashSet<string>();
// The two front claws (bone names read from the SeekerBrute prefab with UnityPy). The slam
// brings one down, then the other; each Hit lands under whichever claw just came down.
private Transform leftClaw;
private Transform rightClaw;
private RavagerRootMotionRelay rootMotion;
private void Start()
{
foreach (Transform bone in GetComponentsInChildren<Transform>(true))
{
if (bone.name == "l.frontfoot") leftClaw = bone;
else if (bone.name == "r.frontfoot") rightClaw = bone;
}
anim = GetComponentInChildren<Animator>();
if (anim == null || anim.runtimeAnimatorController == null) return;
// The same three settings WarVultureVisual.PrepareAnimator uses on its own borrowed
// model, for the same reasons. applyRootMotion=false: the slam's clip carries real
// baked motion, and left at the default Unity would walk the COSTUME out from under
// its wearer - the model has no collider and no gameplay meaning, only the player
// does, and the player already moves through Valheim's own code, not an animation
// clip. fireEvents=false: attack clips carry animation events aimed at
// CharacterAnimEvent, which BuildTemplate already stripped off this model, so left on
// every swing would log "has no receiver" for nothing. cullingMode: keeps the model
// animating even when it is partly off the bottom of the screen, the way a body
// standing close to the camera often is.
anim.applyRootMotion = false;
anim.fireEvents = false;
anim.cullingMode = AnimatorCullingMode.AlwaysAnimate;
// The ram is the exception: its clip's motion moves the PLAYER (see
// Sverm_RavagerRootMotion_Patch). With an OnAnimatorMove receiver on the Animator's
// object, Unity computes the motion and hands it over instead of moving the costume.
rootMotion = anim.gameObject.AddComponent<RavagerRootMotionRelay>();
rootMotion.Animator = anim;
anim.applyRootMotion = true;
foreach (AnimatorControllerParameter param in anim.parameters)
{
if (param.type == AnimatorControllerParameterType.Float && param.name == "forward_speed")
hasForwardSpeed = true;
else if (param.type == AnimatorControllerParameterType.Bool && param.name == "onGround")
hasOnGround = true;
else if (param.type == AnimatorControllerParameterType.Trigger && param.name == "jump")
hasJumpTrigger = true;
else if (param.type == AnimatorControllerParameterType.Bool && param.name == "jump")
hasJumpBool = true;
else if (param.type == AnimatorControllerParameterType.Trigger)
knownTriggers.Add(param.name);
}
Jotunn.Logger.LogInfo($"[Sverm] Ravager Strain model animator: forward_speed={hasForwardSpeed}, " +
$"onGround={hasOnGround}, jump=" +
(hasJumpTrigger ? "trigger" : hasJumpBool ? "bool" : "none") + ".");
}
/// <summary>
/// FOUND IN PLAY: the real body flickered into view on every equipment change elsewhere
/// in the game (a nearby player's gear, a tamed animal, anything that shares
/// VisEquipment's rebuild path) - PlayerVisualHider's own comment already says gear
/// changes make hidden things visible again, which is why it re-sweeps on a timer rather
/// than hiding once. That timer is 0.25s, long enough to be noticed.
///
/// LateUpdate, not Update: Unity runs every component's Update before any component's
/// LateUpdate in a given frame, so this always runs after whatever rebuilt visuals
/// earlier in the same frame, rather than racing it. Re-hiding every single frame the
/// form is up closes the gap the 0.25s timer leaves open, without touching
/// PlayerVisualHider's own interval, which every other race's hidden body still relies on.
/// </summary>
private void LateUpdate()
{
Player player = Player.m_localPlayer;
if (player == null) return;
Transform visual = player.transform.Find("Visual");
PlayerVisualHider.Hide(visual, "sverm-ravager");
}
private void Update()
{
Player player = Player.m_localPlayer;
if (player == null || player.IsDead()) return;
if (isAttacking) return;
bool grounded = player.IsOnGround();
if (hasForwardSpeed)
{
Vector3 velocity = player.GetVelocity();
velocity.y = 0f;
anim.SetFloat("forward_speed", velocity.magnitude);
}
if (hasOnGround) anim.SetBool("onGround", grounded);
if (hasJumpTrigger)
{
// The rising edge only, so a trigger fires once per jump rather than once per
// frame spent airborne.
if (!grounded && wasGrounded) anim.SetTrigger("jump");
}
else if (hasJumpBool)
{
anim.SetBool("jump", !grounded);
}
wasGrounded = grounded;
if (!RaceInput.Allowed || !grounded) return;
// Right click rams, left click bites, middle click slams. All three read the device
// directly (mouse, or its gamepad counterpart - see RaceInput.AttackDown) rather than
// going anywhere near Humanoid.StartAttack, which Sverm_RavagerBlockNativeAttack_Patch
// refuses outright for the whole form - see the class doc for why that turned out to
// be the only reliable option.
if (RaceInput.AttackDown(1))
{
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, "Attack Ram", 2f, false, true));
}
else if (RaceInput.AttackDown(0))
{
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, "Attack Bite", 2f, false, false));
}
else if (RaceInput.AttackDown(2))
{
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, "Attack Slam", 1.2f, true, false));
}
else if ((SvermConfigManagement.RavagerKey.Value.IsDown() ||
RaceInput.ConsumePress(SvermConfigManagement.RavagerKey.Value)) && Time.time >= nextTauntAt)
{
nextTauntAt = Time.time + SvermConfig.RavagerTauntCooldownSeconds;
StartCoroutine(TauntRoutine());
}
}
/// <summary>
/// One swing, timed by the clip itself instead of by fixed delays. Each "Hit" animation
/// event in the clip is a hit here, at the same point of the clip (the bite and the ram
/// have one, the slam has two, one per claw). The player is held still until the
/// animator starts blending out of the attack state, which is when the real Brute can
/// move again. With lunge, the clip's own root motion carries the player forward (the ram).
/// </summary>
private System.Collections.IEnumerator AttackRoutine(SvermRavagerAttacks.Profile profile, string stateName,
float radius, bool slam, bool lunge)
{
isAttacking = true;
bool played = StartAttackState(profile);
if (rootMotion != null) rootMotion.Active = lunge;
int dropSamples = 0;
float[] leftY = new float[ClawHistory];
float[] rightY = new float[ClawHistory];
yield return FollowAttackState(stateName, played, 0f, () =>
{
if (slam) Slam(profile, radius, leftY, rightY, dropSamples);
else ExecuteDamage(profile, radius);
}, () =>
{
if (leftClaw == null || rightClaw == null) return;
leftY[dropSamples % ClawHistory] = leftClaw.position.y;
rightY[dropSamples % ClawHistory] = rightClaw.position.y;
dropSamples++;
});
if (rootMotion != null) rootMotion.Active = false;
isAttacking = false;
}
/// <summary>
/// The taunt, played as a short-cooldown AoE around the player rather than a forward
/// swing - the roar reaches out in every direction, so the sphere is centred on the
/// player instead of offset ahead of them the way AttackRoutine's three do. Deliberately
/// silent: no message, no status effect, nothing in a corner of the screen - just the
/// animation, the sound if one resolves, and the hit. The clip has no Hit event, so the
/// roar lands at TauntHitPoint of the clip.
/// </summary>
private System.Collections.IEnumerator TauntRoutine()
{
isAttacking = true;
SvermRavagerAttacks.Profile profile = SvermRavagerAttacks.Taunt;
bool played = StartAttackState(profile);
PlaySound(SvermConfig.RavagerTauntSoundEffects);
yield return FollowAttackState("Taunt", played, TauntHitPoint, () =>
{
Player player = Player.m_localPlayer;
if (player != null)
ApplyDamageInSphere(player.transform.position + Vector3.up, SvermConfig.RavagerTauntRadius, profile.Damage);
}, null);
isAttacking = false;
}
// 0.3 s into the 2.67 s taunt clip, where the old fixed delay put the roar's hit.
private const float TauntHitPoint = 0.11f;
// Frames of claw height kept to tell which claw just came down (about 0.2 s at 60 fps).
private const int ClawHistory = 12;
private bool StartAttackState(SvermRavagerAttacks.Profile profile)
{
if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f);
if (string.IsNullOrEmpty(profile.Trigger) || !knownTriggers.Contains(profile.Trigger)) return false;
anim.SetTrigger(profile.Trigger);
SvermRavagerForm.PublishAttackTrigger(Player.m_localPlayer, profile.Trigger);
return true;
}
/// <summary>
/// Waits out one attack state frame by frame. Calls onHit at every Hit event of the
/// state's clip (or once at fallbackHit, a 0-1 point of the clip, when the clip has
/// none), and returns once the animator starts leaving the state. If the state never
/// starts (trigger missing), it hits once and returns, so the attack still works.
/// </summary>
private System.Collections.IEnumerator FollowAttackState(string stateName, bool played, float fallbackHit,
System.Action onHit, System.Action eachFrame)
{
float startedAt = Time.time;
bool entered = false;
float[] hits = null;
int nextHit = 0;
while (played && Time.time - startedAt < 8f)
{
eachFrame?.Invoke();
AnimatorStateInfo state;
AnimatorClipInfo[] clips;
bool leaving;
if (!TryGetAttackState(stateName, out state, out clips, out leaving))
{
if (entered || Time.time - startedAt > 0.5f) break;
yield return null;
continue;
}
entered = true;
if (hits == null) hits = ReadHitPoints(clips, fallbackHit);
while (nextHit < hits.Length && state.normalizedTime >= hits[nextHit])
{
onHit();
nextHit++;
}
if (leaving) break;
yield return null;
}
if (!entered) onHit();
}
private bool TryGetAttackState(string stateName, out AnimatorStateInfo state, out AnimatorClipInfo[] clips, out bool leaving)
{
state = anim.GetCurrentAnimatorStateInfo(0);
if (state.IsName(stateName))
{
clips = anim.GetCurrentAnimatorClipInfo(0);
leaving = anim.IsInTransition(0);
return true;
}
leaving = false;
if (anim.IsInTransition(0))
{
state = anim.GetNextAnimatorStateInfo(0);
if (state.IsName(stateName))
{
clips = anim.GetNextAnimatorClipInfo(0);
return true;
}
}
clips = null;
return false;
}
private static float[] ReadHitPoints(AnimatorClipInfo[] clips, float fallbackHit)
{
var points = new System.Collections.Generic.List<float>();
if (clips != null && clips.Length > 0 && clips[0].clip != null && clips[0].clip.length > 0f)
{
AnimationClip clip = clips[0].clip;
foreach (AnimationEvent ev in clip.events)
if (ev.functionName == "Hit") points.Add(ev.time / clip.length);
}
if (points.Count == 0) points.Add(fallbackHit);
points.Sort();
return points.ToArray();
}
/// <summary>
/// One claw of the slam landing: the claw that dropped the most over the last few frames
/// is the one that just struck. Damage and crater go under it, not at a fixed point ahead.
/// </summary>
private void Slam(SvermRavagerAttacks.Profile profile, float radius, float[] leftY, float[] rightY, int samples)
{
Transform claw = StrikingClaw(leftY, rightY, samples);
if (claw == null)
{
ExecuteDamage(profile, radius);
Player player = Player.m_localPlayer;
if (player != null)
DigCrater(player.transform.position + player.transform.forward * SvermConfigManagement.RavagerAttackOffset);
return;
}
ApplyDamageInSphere(claw.position + Vector3.up * 0.5f, radius, profile.Damage);
DigCrater(claw.position);
}
private Transform StrikingClaw(float[] leftY, float[] rightY, int samples)
{
if (leftClaw == null || rightClaw == null || samples == 0) return null;
int oldest = samples < ClawHistory ? 0 : samples % ClawHistory;
float leftDrop = leftY[oldest] - leftClaw.position.y;
float rightDrop = rightY[oldest] - rightClaw.position.y;
return leftDrop >= rightDrop ? leftClaw : rightClaw;
}
/// <summary>Tries each candidate in order and plays the first that resolves, same as SvermRavagerForm.PlayEffect.</summary>
private static void PlaySound(string[] candidates)
{
Player player = Player.m_localPlayer;
if (player == null) return;
foreach (string name in candidates)
{
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(name);
if (prefab == null) continue;
Object.Instantiate(prefab, player.transform.position, Quaternion.identity);
return;
}
}
/// <summary>
/// FenrirBehaviors.ExecuteClawDamage, unchanged in shape: a sphere swept against the same
/// broad layer mask every melee form in this mod already uses.
/// </summary>
private void ExecuteDamage(SvermRavagerAttacks.Profile profile, float radius)
{
Player player = Player.m_localPlayer;
if (player == null) return;
float reach = SvermConfigManagement.RavagerAttackOffset;
Vector3 attackPoint = player.transform.position + player.transform.forward * reach + Vector3.up;
ApplyDamageInSphere(attackPoint, radius, profile.Damage);
}
private const string CraterPrefab = "digg_v3";
private static readonly int GroundMask = LayerMask.GetMask("terrain", "Default", "static_solid", "piece");
/// <summary>
/// The slam digs where it lands, the way the True Form troll's does (TrolTrueFormBehavior.Slam):
/// a pickaxe's dig on bare terrain only. TerrainOp does not check wards on its own, so the
/// ward check is done here.
/// </summary>
private static void DigCrater(Vector3 impact)
{
if (Player.m_localPlayer == null || !SvermConfigManagement.RavagerSlamCrater) return;
if (!Physics.Raycast(impact + Vector3.up * 3f, Vector3.down, out RaycastHit ground, 8f, GroundMask)) return;
if (ground.collider == null || ground.collider.GetComponent<Heightmap>() == null) return;
if (!PrivateArea.CheckAccess(ground.point, 0f, false)) return;
GameObject crater = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(CraterPrefab);
if (crater != null) Object.Instantiate(crater, ground.point, Quaternion.identity);
}
/// <summary>
/// The actual sweep, shared by every attack this form has (the three forward swings and
/// the taunt's own AoE) - only the sphere's centre and radius differ between them.
///
/// m_skill is Swords, deliberately NOT Unarmed: Sverm_Damage_Patch rewrites any Unarmed
/// hit from a Sverm into the Chitin Claws' own tier damage, and that patch fires for THIS
/// call too, since it hooks Character.Damage itself rather than caring who dealt the hit.
/// Swords keeps that rewrite from overwriting the Brute's real numbers with the claws'.
/// </summary>
private static void ApplyDamageInSphere(Vector3 center, float radius, HitData.DamageTypes damage)
{
Player player = Player.m_localPlayer;
if (player == null) return;
int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece",
"piece_nonsolid", "terrain", "character", "character_net", "character_ghost",
"hitbox", "character_noenv", "vehicle");
Collider[] hits = Physics.OverlapSphere(center, radius, layerMask);
var hitObjects = new System.Collections.Generic.HashSet<GameObject>();
foreach (Collider hit in hits)
{
if (hit.gameObject == player.gameObject) continue;
if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == player.gameObject) continue;
IDestructible target = hit.GetComponentInParent<IDestructible>();
if (target == null) continue;
if (target is Character characterTarget && characterTarget == player) continue;
GameObject targetObj = (target as MonoBehaviour)?.gameObject;
if (targetObj != null)
{
if (hitObjects.Contains(targetObj)) continue;
hitObjects.Add(targetObj);
}
Vector3 targetCenter = hit.bounds.center;
Vector3 dirToTarget = (targetCenter - player.transform.position).normalized;
HitData hitData = new HitData();
hitData.m_damage = damage;
hitData.m_point = targetCenter;
hitData.m_dir = dirToTarget;
hitData.m_pushForce = 40f;
hitData.m_skill = Skills.SkillType.Swords;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.m_toolTier = 100;
hitData.SetAttacker(player);
target.Damage(hitData);
}
}
}
}