RacesOfValheim/JotunnModStub/Trol/TrolTrueFormBehavior.cs
kanym b2346c1437 feat(trol): Legacy True Form switch, chosen per player
The Troll Model option becomes Legacy True Form, off by default. On,
True Form is the old one: the player's own Trol grown bigger, weapons
in hand, body untouched, which player model mods such as VRM need.

It is a local preference, not a synced one, so a server cannot force
the troll costume on a VRM user. The owner publishes the choice on the
ZDO and every other client reads it from there, so onlookers see each
Trol the way that Trol's owner picked.
2026-10-17 15:32:06 +02:00

516 lines
23 KiB
C#

using System.Collections;
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Drives the local player's troll: its legs from the hidden player's Animator, its fists from
/// the mouse. FenrirFormBehavior in shape - a trigger on the costume's Animator, then a sweep for
/// whatever is in reach - with two differences. The hit waits for the troll's own OnAttackTrigger
/// (see TrolTrueFormModel) instead of a fixed delay, and the damage is the troll's own, scaled.
///
/// Left click punches, right click slams the ground. With a log in hand they become the troll's
/// two log swings, and each one that lands wears the log down the way a club swing used to.
/// </summary>
public class TrolTrueFormBehavior : MonoBehaviour
{
// Longest a swing waits for the troll's own hit event before landing anyway: a clip with
// no event must not leave the player swinging at nothing.
private const float HitEventTimeout = 1.5f;
private Animator anim;
private Animator playerAnim;
private readonly FormLocomotion locomotion = new FormLocomotion();
private readonly HashSet<string> triggers = new HashSet<string>();
private bool isAttacking;
private float busySince = -1f;
private GameObject heldLog;
private string heldLogName;
public bool IsAttacking => isAttacking;
private void SetAttacking(bool on)
{
isAttacking = on;
TrolTrueFormModel.LocalAttacking = on;
}
private void OnDestroy()
{
TrolTrueFormModel.LocalAttacking = false;
}
private void Start()
{
anim = GetComponentInChildren<Animator>();
Transform visual = Player.m_localPlayer != null ? Player.m_localPlayer.transform.Find("Visual") : null;
if (visual != null) playerAnim = visual.GetComponent<Animator>();
if (anim != null)
{
foreach (AnimatorControllerParameter p in anim.parameters)
{
if (p.type == AnimatorControllerParameterType.Trigger) triggers.Add(p.name);
}
}
}
/// <summary>Re-hides the body every frame; see RavagerFormBehavior.LateUpdate for why a
/// timer is not enough.</summary>
private void LateUpdate()
{
Player player = Player.m_localPlayer;
if (player == null) return;
PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local", keepScale: true);
}
private void Update()
{
Player player = Player.m_localPlayer;
if (player == null || anim == null || playerAnim == null) return;
transform.localScale = Vector3.one * TrolTrueFormModel.ScaleFor(player);
ItemDrop.ItemData right = Traverse.Create(player).Field<ItemDrop.ItemData>("m_rightItem").Value;
TrolTrueFormModel.UpdateHeldLog(gameObject, right?.m_dropPrefab, ref heldLog, ref heldLogName);
if (FormAnimGuard.Stuck(isAttacking, ref busySince))
{
StopAllCoroutines();
SetAttacking(false);
}
if (isAttacking || player.IsDead()) return;
bool grounded = locomotion.Mirror(anim, playerAnim, player.IsCrouching());
if (!grounded || !RaceInput.Allowed) return;
bool log = heldLogName != null;
if (RaceInput.AttackDown(0))
{
Play(log ? TrolTrueFormModel.AttackKind.LogSwingH : TrolTrueFormModel.AttackKind.Punch);
}
else if (RaceInput.AttackDown(1))
{
Play(log ? TrolTrueFormModel.AttackKind.LogSwingV : TrolTrueFormModel.AttackKind.Slam);
}
}
private void Play(TrolTrueFormModel.AttackKind kind)
{
TrolTrueFormModel.Profile profile = TrolTrueFormModel.Get(kind);
// A log swing the troll does not have falls back on the fist, rather than doing nothing.
if (profile == null && kind == TrolTrueFormModel.AttackKind.LogSwingH) profile = TrolTrueFormModel.Get(TrolTrueFormModel.AttackKind.Punch);
if (profile == null && kind == TrolTrueFormModel.AttackKind.LogSwingV) profile = TrolTrueFormModel.Get(TrolTrueFormModel.AttackKind.Slam);
if (profile == null) return;
bool log = kind == TrolTrueFormModel.AttackKind.LogSwingH || kind == TrolTrueFormModel.AttackKind.LogSwingV;
// The slam goes by what the key means, not by the troll's attack type: troll_groundslam
// is a Vertical attack in vanilla, not an Area one, so asking the type sent every slam
// down the punch's sweep - no dust, no crater, only the damage.
bool slam = kind == TrolTrueFormModel.AttackKind.Slam && profile == TrolTrueFormModel.Get(TrolTrueFormModel.AttackKind.Slam);
StartCoroutine(AttackRoutine(profile, log, slam));
}
/// <summary>
/// Plays the troll's throw for TrolRace's Throw Rock and holds the troll still through it.
/// Returns the event count to wait on, or -1 if the troll has no throw to play.
/// </summary>
public int PlayThrow()
{
TrolTrueFormModel.Profile profile = TrolTrueFormModel.Get(TrolTrueFormModel.AttackKind.Throw);
if (profile == null || isAttacking) return -1;
int baseline = TrolTrueFormModel.AttackEvents;
StartCoroutine(ThrowRoutine(profile));
return baseline;
}
private IEnumerator ThrowRoutine(TrolTrueFormModel.Profile profile)
{
SetAttacking(true);
Fire(profile.Trigger);
yield return WaitForClip();
SetAttacking(false);
}
private IEnumerator AttackRoutine(TrolTrueFormModel.Profile profile, bool log, bool slam)
{
SetAttacking(true);
Player player = Player.m_localPlayer;
int baseline = TrolTrueFormModel.AttackEvents;
Fire(profile.Trigger);
profile.Shared.m_startEffect.Create(player.transform.position, player.transform.rotation, player.transform);
float started = Time.time;
while (TrolTrueFormModel.AttackEvents == baseline && Time.time - started < HitEventTimeout)
{
yield return null;
}
if (player != null && !player.IsDead())
{
float scale = transform.localScale.x;
int landed;
if (slam)
{
landed = TrolTrueFormHit.Slam(player, profile, scale);
}
else
{
profile.Shared.m_triggerEffect.Create(player.transform.position, player.transform.rotation, player.transform);
landed = TrolTrueFormHit.Sweep(player, profile, scale);
}
if (landed > 0)
{
player.RaiseSkill(Skills.SkillType.Clubs, 1f);
if (log) WearLog(player);
}
}
yield return WaitForClip(Time.time - started);
SetAttacking(false);
}
private void Fire(string trigger)
{
if (anim == null || string.IsNullOrEmpty(trigger) || !triggers.Contains(trigger)) return;
try { anim.SetFloat("forward_speed", 0f); } catch {}
try { anim.SetFloat("sideway_speed", 0f); } catch {}
anim.SetTrigger(trigger);
TrolTrueFormModel.PublishAttackTrigger(Player.m_localPlayer, trigger);
}
/// <summary>
/// Holds the lock until the attack clip has played out. The clip is read off the Animator a
/// frame after the trigger, when the transition into it has started; the length is clamped
/// so a wrong guess can neither cut a swing short nor freeze the troll.
/// </summary>
private IEnumerator WaitForClip(float alreadySpent = 0f)
{
yield return null;
float length = 1.2f;
if (anim != null)
{
AnimatorClipInfo[] clips = anim.IsInTransition(0) ? anim.GetNextAnimatorClipInfo(0) : anim.GetCurrentAnimatorClipInfo(0);
if (clips != null && clips.Length > 0 && clips[0].clip != null) length = clips[0].clip.length;
}
float remaining = Mathf.Clamp(length, 0.6f, 3f) - alreadySpent;
if (remaining > 0f) yield return new WaitForSeconds(remaining);
}
/// <summary>The same wear a club swing put on the log, per swing that lands. TrolRace.Update
/// breaks it once it reaches zero.</summary>
private static void WearLog(Player player)
{
ItemDrop.ItemData right = Traverse.Create(player).Field<ItemDrop.ItemData>("m_rightItem").Value;
if (right == null || right.m_dropPrefab == null || !right.m_dropPrefab.name.StartsWith("TrolWeapon_")) return;
right.m_durability = Mathf.Max(0f, right.m_durability - TrolConfig.LogWeaponDurabilityDrainPerHit.Value);
}
}
/// <summary>
/// One troll blow against whatever is in reach. FenrirFormBehavior.ExecuteClawDamage's shape and
/// cover test, with the reach taken off the troll's own weapon and multiplied by how big the
/// costume is - a troll's arm is a troll's arm, at whatever size it is worn.
/// </summary>
internal static class TrolTrueFormHit
{
private const string FormLabel = "Troll";
private static readonly int Mask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece",
"piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox",
"character_noenv", "vehicle");
private const string SlamAoeFallback = "troll_groundslam_aoe";
private const string CraterPrefab = "digg_v3";
private static readonly int GroundMask = LayerMask.GetMask("terrain", "Default", "static_solid", "piece");
/// <summary>
/// The ground slam, done the way the troll does it: its attack's own spawn-on-trigger, the
/// troll_groundslam_aoe that carries the dust and the area hit. Set up with this player's
/// damage instead of the troll's (m_useAttackSettings) and kept off friends. The first
/// version swept a sphere and spawned nothing, so a slam that hit no creature looked like
/// nothing had happened at all.
///
/// It also breaks things: the slam's damage gets chop and pickaxe at least equal to its
/// blunt, so trees, rocks and ore around the fists take the blow. With Ground Slam Crater on,
/// the ground gives way too - a pickaxe's dig, which TerrainOp does not check against wards on
/// its own, so the ward check is done here.
/// </summary>
/// <returns>1 if the slam went off, so the caller raises the skill; the AoE does its own hits.</returns>
public static int Slam(Player player, TrolTrueFormModel.Profile profile, float costumeScale)
{
float range = Mathf.Max(2f, profile.Range * costumeScale * TrolConfig.TrueFormAttackReach.Value);
Vector3 impact = player.transform.position + player.transform.forward * (range * 0.5f);
// Down onto whatever is under the fists, so the dust and the crater sit on the ground.
bool onTerrain = false;
if (Physics.Raycast(impact + Vector3.up * 3f, Vector3.down, out RaycastHit ground, 8f, GroundMask))
{
impact = ground.point;
onTerrain = ground.collider != null && ground.collider.GetComponent<Heightmap>() != null;
}
HitData.DamageTypes damage = TrolTrueFormModel.DamageFor(player, profile);
damage.m_chop = Mathf.Max(damage.m_chop, damage.m_blunt);
damage.m_pickaxe = Mathf.Max(damage.m_pickaxe, damage.m_blunt);
HitData hitData = new HitData();
hitData.m_damage = damage;
hitData.m_pushForce = profile.PushForce;
hitData.m_skill = Skills.SkillType.Clubs;
hitData.m_toolTier = (short)profile.ToolTier;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.SetAttacker(player);
profile.Shared.m_triggerEffect.Create(impact, player.transform.rotation);
profile.Shared.m_hitTerrainEffect.Create(impact, Quaternion.identity);
GameObject aoePrefab = profile.Shared.m_attack.m_spawnOnTrigger;
if (aoePrefab == null) aoePrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(SlamAoeFallback);
bool spawned = false;
if (aoePrefab != null)
{
GameObject instance = Object.Instantiate(aoePrefab, impact, Quaternion.identity);
Aoe aoe = instance.GetComponent<Aoe>();
if (aoe != null)
{
aoe.m_useAttackSettings = true;
aoe.m_hitFriendly = false;
aoe.m_hitOwner = false;
aoe.m_hitProps = true;
aoe.m_radius = Mathf.Max(aoe.m_radius, range * 0.6f);
aoe.Setup(player, player.transform.forward, -1f, hitData, null, null);
spawned = true;
}
else
{
Object.Destroy(instance);
}
}
// No Aoe to borrow: the sphere, centred on the impact, so the slam still hits.
if (!spawned) SphereHit(player, impact + Vector3.up, range * 0.7f, 180f, damage, profile);
if (TrolConfig.TrueFormSlamCrater.Value && onTerrain && PrivateArea.CheckAccess(impact, 0f, false))
{
GameObject crater = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(CraterPrefab);
if (crater != null) Object.Instantiate(crater, impact, Quaternion.identity);
}
Jotunn.Logger.LogInfo($"[Trol] Ground slam: aoe '{aoePrefab?.name ?? "none"}' spawned={spawned}, " +
$"range {range:0.0}, onTerrain={onTerrain}.");
return 1;
}
/// <returns>How many things the blow landed on.</returns>
public static int Sweep(Player player, TrolTrueFormModel.Profile profile, float costumeScale)
{
Vector3 pos = player.transform.position;
Vector3 forward = player.transform.forward;
float range = Mathf.Max(2f, profile.Range * costumeScale * TrolConfig.TrueFormAttackReach.Value);
Vector3 center = pos + forward * (range * 0.55f) + Vector3.up * Mathf.Max(1f, profile.Height * costumeScale);
float radius = range * 0.6f + 0.75f;
float halfAngle = Mathf.Max(75f, profile.Angle * 0.5f);
return SphereHit(player, center, radius, halfAngle, TrolTrueFormModel.DamageFor(player, profile), profile);
}
private static int SphereHit(Player player, Vector3 center, float radius, float halfAngle,
HitData.DamageTypes damage, TrolTrueFormModel.Profile profile)
{
Vector3 pos = player.transform.position;
Vector3 forward = player.transform.forward;
Collider[] hits = Physics.OverlapSphere(center, radius, Mask);
FormMelee.LogSwing(FormLabel, hits.Length);
var done = new HashSet<GameObject>();
int landed = 0;
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 || (target is Character c && c == player)) continue;
GameObject targetObj = (target as MonoBehaviour)?.gameObject;
if (targetObj != null && done.Contains(targetObj)) continue;
Vector3 targetCenter = hit.bounds.center;
Vector3 flat = targetCenter - pos;
flat.y = 0f;
float angle = flat.sqrMagnitude > 0.0001f ? Vector3.Angle(forward, flat) : 0f;
if (angle > halfAngle)
{
FormMelee.LogMiss(FormLabel, hit, $"outside the swing arc ({angle:0} deg)");
continue;
}
Vector3 eye = player.GetEyePoint();
if (!FormMelee.CanReach(eye, center, hit, target, out string cover))
{
FormMelee.LogMiss(FormLabel, hit, "no clear line, blocked by '" + cover + "'");
continue;
}
HitData hitData = new HitData();
hitData.m_damage = damage;
hitData.m_point = targetCenter;
hitData.m_dir = (targetCenter - pos).normalized;
hitData.m_pushForce = profile.PushForce;
hitData.m_skill = Skills.SkillType.Clubs;
hitData.m_toolTier = (short)profile.ToolTier;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.SetAttacker(player);
if (targetObj != null) done.Add(targetObj);
FormMelee.LogHit(FormLabel, target, damage.GetTotalDamage());
target.Damage(hitData);
profile.Shared.m_hitEffect.Create(targetCenter, Quaternion.identity);
landed++;
}
return landed;
}
}
/// <summary>
/// The troll every other client sees. RemoteFenrirAnimator in shape: legs from the remote
/// player's own Animator, which ZSyncAnimation keeps fed over the network, and attacks replayed
/// from the trigger the owner publishes. Sized and given its log the same way as the owner's.
/// </summary>
public class RemoteTrolTrueFormAnimator : MonoBehaviour
{
private Player player;
private Animator anim;
private Animator playerAnim;
private ZNetView nview;
private string lastAttack;
private readonly FormLocomotion locomotion = new FormLocomotion();
private GameObject heldLog;
private string heldLogName;
private void LateUpdate()
{
if (player == null) return;
PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-remote", keepScale: true);
}
private void Update()
{
if (player == null) player = GetComponentInParent<Player>();
if (player == null) return;
if (nview == null) nview = player.GetComponent<ZNetView>();
if (anim == null) anim = GetComponentInChildren<Animator>();
if (playerAnim == null)
{
Transform visual = player.transform.Find("Visual");
if (visual != null) playerAnim = visual.GetComponent<Animator>();
}
if (anim == null || playerAnim == null || nview == null || !nview.IsValid()) return;
transform.localScale = Vector3.one * TrolTrueFormModel.ScaleFor(player);
int rightHash = nview.GetZDO().GetInt(ZDOVars.s_rightItem, 0);
GameObject rightPrefab = rightHash != 0 && ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(rightHash) : null;
TrolTrueFormModel.UpdateHeldLog(gameObject, rightPrefab, ref heldLog, ref heldLogName);
ReplayAttack();
locomotion.Mirror(anim, playerAnim, player.IsCrouching());
}
private void ReplayAttack()
{
string current = nview.GetZDO().GetString(TrolTrueFormModel.AttackTriggerKey, "");
// The first look only records what is there, so a punch from an earlier True Form does
// not replay the moment this troll is built.
if (lastAttack == null) { lastAttack = current; return; }
if (string.IsNullOrEmpty(current) || current == lastAttack) return;
lastAttack = current;
int seqAt = current.LastIndexOf('#');
string trigger = seqAt >= 0 ? current.Substring(0, seqAt) : current;
foreach (AnimatorControllerParameter p in anim.parameters)
{
if (p.type == AnimatorControllerParameterType.Trigger && p.name == trigger)
{
try { anim.SetFloat("forward_speed", 0f); } catch {}
anim.SetTrigger(trigger);
break;
}
}
}
}
/// <summary>
/// Puts the troll on every other client, from the True Form flag Trol_PlayerUpdate_Patch already
/// publishes for sizing. Sverm_RavagerRemoteVisuals_Patch's arrangement.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
public static class Trol_TrueFormRemoteVisuals_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || !__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null || player.IsOwner()) return; // The owner's own troll: TrolTrueFormModel.Tick.
ZNetView nview = player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return;
ZDO zdo = nview.GetZDO();
// The owner's choice, not this client's: see TrolTrueFormModel.LegacyKey.
bool active = !zdo.GetBool(TrolTrueFormModel.LegacyKey, false) &&
!player.IsDead() &&
zdo.GetString("RacesOfValheim_Race", "Human") == "Trol" &&
zdo.GetBool(Trol_PlayerUpdate_Patch.TrueFormKey, false);
Transform existing = player.transform.Find(TrolTrueFormModel.RemoteModelName);
Transform playerVisual = player.transform.Find("Visual");
if (!active)
{
if (existing != null)
{
existing.gameObject.SetActive(false);
Object.Destroy(existing.gameObject);
PlayerVisualHider.Show(playerVisual, "trol-trueform-remote-revert", keepScale: true);
}
return;
}
if (existing == null)
{
GameObject model = TrolTrueFormModel.Spawn(player, TrolTrueFormModel.RemoteModelName);
if (model == null) return;
model.AddComponent<RemoteTrolTrueFormAnimator>();
}
PlayerVisualHider.Hide(playerVisual, "trol-trueform-remote", keepScale: true);
}
}
}