Merge branch 'main' into localisation

This commit is contained in:
kanym 2026-10-17 15:32:06 +02:00
commit e38df0b7e0
6 changed files with 1067 additions and 6 deletions

View file

@ -40,6 +40,9 @@ namespace RacesOfValheim
private static readonly string[] LocalKeyParts =
{
"marker light", "tint", "colour", "color", "glow", "swarm scale", "log rounds", "debug",
// Each player picks their own True Form: a player model mod (VRM and the like) breaks
// under the troll costume, so a server cannot be allowed to force the costume on.
"legacy true form",
};
public static void Apply(ConfigFile config)

View file

@ -37,14 +37,18 @@ namespace RacesOfValheim
private float m_nextLog;
private string m_context = "";
public static void Hide(Transform playerVisual, string context)
/// <param name="keepScale">Leave the Visual's scale alone. For a body that is meant to be
/// sized while hidden: the Trol's True Form troll stands as tall as the Visual does, and
/// resetting it here every frame fought Trol_PlayerUpdate_Patch growing it back - the troll
/// pulsed several times a second and never reached full size.</param>
public static void Hide(Transform playerVisual, string context, bool keepScale = false)
{
if (playerVisual == null) return;
// Undo the two older ways this body could have been hidden, so a form entered right
// after one of those code paths still starts from a sane state.
if (!playerVisual.gameObject.activeSelf) playerVisual.gameObject.SetActive(true);
if (playerVisual.localScale != Vector3.one) playerVisual.localScale = Vector3.one;
if (!keepScale && playerVisual.localScale != Vector3.one) playerVisual.localScale = Vector3.one;
// Belt and braces: if anything else ever does deactivate the Visual, at least keep the
// animator from snapping back to its spawn state.
@ -68,12 +72,12 @@ namespace RacesOfValheim
}
}
public static void Show(Transform playerVisual, string context)
public static void Show(Transform playerVisual, string context, bool keepScale = false)
{
if (playerVisual == null) return;
if (!playerVisual.gameObject.activeSelf) playerVisual.gameObject.SetActive(true);
if (playerVisual.localScale != Vector3.one) playerVisual.localScale = Vector3.one;
if (!keepScale && playerVisual.localScale != Vector3.one) playerVisual.localScale = Vector3.one;
PlayerVisualHider hider = playerVisual.GetComponent<PlayerVisualHider>();
if (hider == null || !hider.enabled) return;

View file

@ -51,6 +51,11 @@ namespace RacesOfValheim
public static ConfigEntry<float> TrueFormCooldown;
public static ConfigEntry<float> TrueFormScaleNormal;
public static ConfigEntry<float> TrueFormScaleAdvanced;
public static ConfigEntry<bool> TrueFormLegacy;
public static ConfigEntry<float> TrueFormModelSize;
public static ConfigEntry<float> TrueFormTrollDamageShare;
public static ConfigEntry<float> TrueFormAttackReach;
public static ConfigEntry<bool> TrueFormSlamCrater;
// ─── Log Weapon (tier 7+) ──────────────────────────────────────────────
public static ConfigEntry<float> LogWeaponMaxDurability;
@ -133,6 +138,16 @@ namespace RacesOfValheim
new ConfigDescription("Model scale while in True Form, tier 5-6.", new AcceptableValueRange<float>(1f, 4f)));
TrueFormScaleAdvanced = config.Bind(trueForm, "Scale (Tier 7+)", 2.5f,
new ConfigDescription("Model scale while in True Form, tier 7+.", new AcceptableValueRange<float>(1f, 4f)));
TrueFormLegacy = config.Bind(trueForm, "Legacy True Form", false,
new ConfigDescription("Off: True Form wears Valheim's own troll, with its punch and ground slam instead of your weapons. On: the old True Form, your own Trol grown bigger with weapons in hand. Turn it on if you use a player model mod such as VRM, which needs the player's body to stay visible. Your own choice: other players see you the way you picked."));
TrueFormModelSize = config.Bind(trueForm, "Troll Model Size", 1f,
new ConfigDescription("How tall the troll stands, as a share of the True Form size set by Scale above. 1 = exactly as tall as the old True Form.", new AcceptableValueRange<float>(0.5f, 2f)));
TrueFormTrollDamageShare = config.Bind(trueForm, "Troll Attack Damage", 0.5f,
new ConfigDescription("Share of a real troll's damage each troll attack deals. Your Clubs skill then scales it the way it scales a club, and the True Form Melee Bonus and tier bonuses add on top.", new AcceptableValueRange<float>(0.1f, 2f)));
TrueFormAttackReach = config.Bind(trueForm, "Troll Attack Reach", 1.3f,
new ConfigDescription("Multiplies how far the troll's punch and slam reach and how wide they hit. 1 = a real troll's reach at the size you stand.", new AcceptableValueRange<float>(0.5f, 3f)));
TrueFormSlamCrater = config.Bind(trueForm, "Ground Slam Crater", true,
new ConfigDescription("The ground slam digs into the ground where it lands, like a pickaxe blow. Never inside a ward you have no access to."));
const string logWeapon = "Trol - Log Weapon";
LogWeaponMaxDurability = config.Bind(logWeapon, "Max Durability", 6f,

View file

@ -153,6 +153,10 @@ namespace RacesOfValheim
private void Update()
{
// Before the race check, on purpose: a race change or a death has to take the troll
// costume off, and nothing below the check runs for them any more.
TrolTrueFormModel.Tick(Player.m_localPlayer);
if (!IsTrol()) return;
if (RaceInput.Allowed)
@ -247,6 +251,8 @@ namespace RacesOfValheim
if (nview != null && nview.IsValid()) nview.GetZDO().Set(Trol_PlayerUpdate_Patch.TrueFormKey, false);
}
if (TrolTrueFormModel.RemoveLocal(player)) hadForm = true;
isTransforming = false;
wasTrueFormActive = false;
return hadForm;
@ -402,8 +408,20 @@ namespace RacesOfValheim
Player.m_localPlayer.GetInventory().RemoveItem(rightItem);
}
// Wait a moment for the animation to reach the throw point
yield return new WaitForSeconds(0.4f);
// Wait a moment for the animation to reach the throw point. Wearing the troll, that is
// the troll's own throw, and the rock leaves the hand on its OnAttackTrigger.
TrolTrueFormBehavior troll = isTrueForm ? FindObjectOfType<TrolTrueFormBehavior>() : null;
int baseline = troll != null ? troll.PlayThrow() : -1;
if (baseline >= 0)
{
float started = Time.time;
while (TrolTrueFormModel.AttackEvents == baseline && Time.time - started < 1.5f) yield return null;
}
else
{
yield return new WaitForSeconds(0.4f);
}
if (Player.m_localPlayer == null) yield break;
Vector3 spawnPos = Player.m_localPlayer.GetEyePoint() + Player.m_localPlayer.GetLookDir() * 1.5f;

View file

@ -0,0 +1,516 @@
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);
}
}
}

View file

@ -0,0 +1,505 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// True Form wears Valheim's own forest troll instead of a scaled-up player.
///
/// Built the way the Fenrir forms are, not the way the Sverm's Ravager is: the troll's Visual is
/// instantiated live under the player, CharacterAnimEvent and AnimationEffect included. That
/// costs a FormFootsteps.Detach, and in return the troll's own clips play their own sounds and,
/// more to the point here, fire OnAttackTrigger at the exact frame a fist lands. That event
/// resolves to the PLAYER (the first Character up the hierarchy), and
/// Trol_TrueFormAttackTrigger_Patch catches it there - so every hit lands on the troll's own
/// timing rather than on a delay somebody guessed.
///
/// SIZE. The costume does not have a size of its own. Every frame it is sized to stand as tall as
/// the player's hidden Visual would - the same Visual Trol_PlayerUpdate_Patch already grows from
/// 1.2-1.3 to the True Form scale, on the owner's client and every onlooker's. So the grow-in, the
/// shrink back and the size other players see all come from code that already worked, and
/// "Scale" / "Scale (Tier 7+)" keep meaning what they meant: how many player heights tall.
///
/// ATTACKS. Read once off the troll's own weapons (Humanoid.m_defaultItems and friends): the
/// trigger each one plays, its damage, its reach. Nothing is cloned or equipped. The damage is a
/// share of the troll's (Troll Attack Damage), scaled by the player's Clubs skill exactly the way
/// a weapon is, and hit as Clubs - so Trol_Character_ApplyDamage_Patch adds the True Form and tier
/// bonuses on top just as it did for a club in hand.
/// </summary>
public static class TrolTrueFormModel
{
public const string Creature = "Troll";
public const string LocalModelName = "TrolTrueFormModel";
public const string RemoteModelName = "TrolTrueFormRemoteModel";
// Published by the owner after every trigger it fires, with a running count so the same
// punch twice in a row still reads as two - see FenrirAttackSync.
public const string AttackTriggerKey = "RacesOfValheim_TrolTrueFormAttack";
// The owner's Legacy True Form choice, so every other client draws this Trol the way its
// owner picked rather than the way the onlooker's own setting says.
public const string LegacyKey = "RacesOfValheim_TrolTrueFormLegacy";
private static int attackSeq;
private static readonly int TrueFormHash = "SE_TrolTrueForm".GetStableHashCode();
public enum AttackKind { Punch, Slam, Throw, LogSwingH, LogSwingV }
public class Profile
{
public string Source;
public string Trigger;
public HitData.DamageTypes Damage;
public Attack.AttackType Type;
public float Range;
public float Height;
public float Angle;
public float PushForce;
public int ToolTier;
public ItemDrop.ItemData.SharedData Shared;
// The weapon's own model, as VisEquipment would hang it in the troll's hand. Only the
// log swings have one worth showing.
public GameObject Attach;
}
private static readonly Dictionary<AttackKind, Profile> profiles = new Dictionary<AttackKind, Profile>();
private static bool profilesRead;
// Measured once off the prefab: how tall the troll stands at scale 1.
private static float trollHeight = -1f;
private static string rightHandPath;
private static readonly HashSet<string> logged = new HashSet<string>();
private static GameObject localModel;
private static int attackEvents;
public static bool LocalActive => localModel != null;
/// <summary>True while the local troll is in the middle of a swing, a slam or a throw.
/// Trol_TrueFormHoldStill_Patch holds the player still for exactly that long.</summary>
public static bool LocalAttacking { get; set; }
/// <summary>How many OnAttackTrigger events the local troll has fired. Attack routines
/// remember the count and wait for it to move.</summary>
public static int AttackEvents => attackEvents;
public static void NotifyAttackTrigger() => attackEvents++;
// ─── Lifecycle ───────────────────────────────────────────────────────
/// <summary>
/// Called every frame from TrolRace.Update, before its race check, so a race change, a death
/// or the form running out all take the costume off even though nothing else in TrolRace
/// looks at the player any more by then.
/// </summary>
public static void Tick(Player player)
{
if (player == null || player != Player.m_localPlayer) return;
bool legacy = TrolConfig.TrueFormLegacy.Value;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetBool(LegacyKey, false) != legacy)
{
nview.GetZDO().Set(LegacyKey, legacy);
}
bool wanted = !legacy &&
!player.IsDead() &&
TrolRace.IsTrol() &&
player.GetSEMan().HaveStatusEffect(TrueFormHash);
if (wanted && localModel == null) SpawnLocal(player);
else if (!wanted && localModel != null) RemoveLocal(player);
}
private static void SpawnLocal(Player player)
{
localModel = Spawn(player, LocalModelName);
if (localModel == null) return;
localModel.AddComponent<TrolTrueFormBehavior>();
PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local", keepScale: true);
GameObject smoke = PrefabManager.Cache.GetPrefab<GameObject>("vfx_corpse_destruction_medium");
if (smoke != null) Object.Instantiate(smoke, player.transform.position + Vector3.up, Quaternion.identity);
}
/// <summary>Takes the costume off and gives the body back. Safe to call when there is none.</summary>
public static bool RemoveLocal(Player player)
{
if (localModel == null) return false;
// SetActive first: Destroy waits for the end of the frame, and the behaviour's
// LateUpdate would hide the body again after the Show below. Same trap
// SvermRavagerForm.Exit documents.
localModel.SetActive(false);
Object.Destroy(localModel);
localModel = null;
LocalAttacking = false;
if (player != null) PlayerVisualHider.Show(player.transform.Find("Visual"), "trol-trueform-revert", keepScale: true);
return true;
}
/// <summary>
/// The troll's Visual, under the given player. Shared by the owner's copy and every
/// onlooker's, so both look alike; only the driving component differs.
/// </summary>
public static GameObject Spawn(Player player, string name)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(Creature);
Transform source = prefab != null ? prefab.transform.Find("Visual") : null;
if (source == null)
{
Jotunn.Logger.LogWarning($"[Trol] No '{Creature}' Visual to build True Form from; staying in the old shape.");
return null;
}
MeasureTroll(prefab);
GameObject model = Object.Instantiate(source.gameObject, player.transform);
model.name = name;
model.transform.localPosition = Vector3.zero;
model.transform.localRotation = Quaternion.identity;
model.transform.localScale = Vector3.one * ScaleFor(player);
FormFootsteps.Detach(model, Creature);
Animator anim = model.GetComponentInChildren<Animator>(true);
if (anim != null)
{
anim.cullingMode = AnimatorCullingMode.AlwaysAnimate;
if (anim.GetComponent("AnimationEffect") == null) anim.gameObject.AddComponent<FormAnimEventSound>();
}
Tint(model, SkinColorOf(player));
return model;
}
/// <summary>
/// The costume's scale for this player right now: as tall as their Visual stands, in
/// player heights, times the Troll Model Size setting.
/// </summary>
public static float ScaleFor(Player player)
{
if (player == null || trollHeight <= 0f) return 1f;
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
float visualScale = visual != null ? visual.transform.localScale.y : 1f;
CapsuleCollider capsule = player.GetComponent<CapsuleCollider>();
float playerHeight = capsule != null ? capsule.height : 1.85f;
return playerHeight * visualScale / trollHeight * TrolConfig.TrueFormModelSize.Value;
}
private static void MeasureTroll(GameObject prefab)
{
if (trollHeight > 0f) return;
CapsuleCollider capsule = prefab.GetComponent<CapsuleCollider>();
trollHeight = capsule != null ? capsule.height * prefab.transform.localScale.y : 0f;
if (trollHeight <= 0.5f) trollHeight = 4.5f;
// Where the troll holds its log: VisEquipment knows, so ask it rather than guess bones.
VisEquipment vis = prefab.GetComponent<VisEquipment>();
Transform hand = vis != null ? vis.m_rightHand : null;
Transform visualRoot = prefab.transform.Find("Visual");
if (hand != null && visualRoot != null && hand.IsChildOf(visualRoot))
{
rightHandPath = PathFrom(visualRoot, hand);
}
Jotunn.Logger.LogInfo($"[Trol] True Form model: '{Creature}' stands {trollHeight:0.00} m at scale 1, " +
$"right hand '{rightHandPath ?? "not found"}'.");
}
private static string PathFrom(Transform root, Transform child)
{
var parts = new List<string>();
for (Transform t = child; t != null && t != root; t = t.parent) parts.Insert(0, t.name);
return string.Join("/", parts);
}
// ─── Looks ───────────────────────────────────────────────────────────
/// <summary>The colour this Trol picked in Trol - Appearance, as published on their ZDO.</summary>
public static Color SkinColorOf(Player player)
{
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview != null && nview.IsValid())
{
Vector3 v = nview.GetZDO().GetVec3(TrolSkinColorPatch.SkinColorKey, new Vector3(-1f, -1f, -1f));
if (v.x >= 0f) return new Color(v.x, v.y, v.z, 1f);
}
return player == Player.m_localPlayer ? TrolConfig.SkinColor.Value : TrolConfig.DefaultSkinColor;
}
// The vanilla forest troll's own colour, as near as a single swatch gets: the same value the
// Skin Color description recommends for "the look of Valheim's own trolls".
private static readonly Color VanillaTrollColor = new Color(0x7F / 255f, 0xA8 / 255f, 0xC9 / 255f, 1f);
/// <summary>
/// Shifts the troll's colour toward the player's skin colour, the way Valheim recolours a
/// starred creature: LevelEffects writes _Hue, _Saturation and _Value on the creature
/// shader. The first version multiplied _Color, which this shader does not read, so the
/// troll stayed vanilla blue. The shift is the distance from the vanilla troll's colour to
/// the chosen one, so the default Trol skin gives a troll close to its own colour and the
/// texture's shading survives whatever hue is picked.
/// </summary>
private static void Tint(GameObject model, Color skin)
{
Color.RGBToHSV(VanillaTrollColor, out float baseH, out float baseS, out float baseV);
Color.RGBToHSV(skin, out float h, out float s, out float v);
float hue = Mathf.Repeat(h - baseH + 0.5f, 1f) - 0.5f;
float saturation = Mathf.Clamp(s - baseS, -1f, 1f);
// Value is halved: the swatch reads darker on the skin than it looks in the picker (the
// Skin Color description says as much), and a full shift took the troll to near black.
float value = Mathf.Clamp((v - baseV) * 0.5f, -1f, 1f);
int tinted = 0;
foreach (Renderer r in model.GetComponentsInChildren<Renderer>(true))
{
if (r is ParticleSystemRenderer) continue;
foreach (Material m in r.materials)
{
if (m == null || !m.HasProperty("_Hue")) continue;
m.SetFloat("_Hue", hue);
if (m.HasProperty("_Saturation")) m.SetFloat("_Saturation", saturation);
if (m.HasProperty("_Value")) m.SetFloat("_Value", value);
tinted++;
}
}
if (logged.Add("tint/" + model.name))
{
Jotunn.Logger.LogInfo($"[Trol] True Form tint: hue {hue:+0.00;-0.00}, saturation {saturation:+0.00;-0.00}, " +
$"value {value:+0.00;-0.00} on {tinted} material(s).");
}
}
/// <summary>
/// Puts a copy of the held Trol log in the troll's right hand, or takes it away. Called every
/// frame by both drivers with whatever the player has in their right hand.
/// </summary>
public static void UpdateHeldLog(GameObject model, GameObject itemPrefab, ref GameObject current, ref string currentName)
{
string wanted = itemPrefab != null && itemPrefab.name.StartsWith("TrolWeapon_") ? itemPrefab.name : null;
if (wanted == currentName) return;
if (current != null) Object.Destroy(current);
current = null;
currentName = wanted;
if (wanted == null || rightHandPath == null) return;
Transform hand = model.transform.Find(rightHandPath);
if (hand == null) return;
// The troll's OWN log, not the Trol's. The Trol's was built for a person's hand - turned
// 90 degrees, pushed 1.5 m along it, scaled to 0.4 - and in the troll's fist that came
// out huge and pointing the wrong way. The troll's log weapon carries a model made for
// exactly this bone, and hanging it the way VisEquipment.AttachItem does (zero offset,
// no rotation, its own scale) puts it where vanilla puts it.
Profile log = Get(AttackKind.LogSwingH) ?? Get(AttackKind.LogSwingV);
GameObject source = log?.Attach;
if (source == null) return;
// An item's "attach" child is stored INACTIVE in its prefab; VisEquipment.AttachItem
// switches it on after the Instantiate. Copied as it was, the log hung in the fist
// switched off - invisible, and it looked as if the Trol held nothing.
current = Object.Instantiate(source);
current.SetActive(true);
current.name = "TrolTrueFormLog";
foreach (Collider c in current.GetComponentsInChildren<Collider>(true)) Object.Destroy(c);
// Hung the way AttachItem hangs it: on the joint at zero, then the item's equipoffset.
current.transform.SetParent(hand, false);
current.transform.localPosition = Vector3.zero;
current.transform.localRotation = Quaternion.identity;
Transform offset = source.transform.parent != null ? source.transform.parent.Find("equipoffset") : null;
if (offset != null)
{
current.transform.localPosition += offset.position;
current.transform.localRotation *= offset.rotation;
}
// AttachItem keeps the attach at its own WORLD size, and a vanilla troll stands at scale 1.
// This one is worn smaller or bigger, so the log takes the costume's share on top. Once
// set, the hand carries it through the grow and shrink like any child.
float handScale = hand.lossyScale.x;
float costume = model.transform.localScale.x;
current.transform.localScale = handScale > 0.0001f
? source.transform.localScale * (costume / handScale)
: source.transform.localScale;
if (logged.Add("log/" + source.name))
{
Jotunn.Logger.LogInfo($"[Trol] True Form log '{log.Source}' in hand: hand scale {handScale:0.###}, " +
$"costume {costume:0.###}, offset {(offset != null ? "yes" : "no")}.");
}
}
// ─── Attacks ─────────────────────────────────────────────────────────
public static Profile Get(AttackKind kind)
{
EnsureProfiles();
profiles.TryGetValue(kind, out Profile p);
return p;
}
private static void EnsureProfiles()
{
if (profilesRead) return;
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(Creature);
Humanoid humanoid = prefab != null ? prefab.GetComponent<Humanoid>() : null;
if (humanoid == null) return;
profilesRead = true;
var weapons = new List<GameObject>();
if (humanoid.m_defaultItems != null) weapons.AddRange(humanoid.m_defaultItems);
if (humanoid.m_randomWeapon != null) weapons.AddRange(humanoid.m_randomWeapon);
if (humanoid.m_randomSets != null)
{
foreach (Humanoid.ItemSet set in humanoid.m_randomSets)
{
if (set?.m_items != null) weapons.AddRange(set.m_items);
}
}
foreach (GameObject weapon in weapons)
{
ItemDrop drop = weapon != null ? weapon.GetComponent<ItemDrop>() : null;
ItemDrop.ItemData.SharedData shared = drop?.m_itemData?.m_shared;
if (shared?.m_attack == null || string.IsNullOrEmpty(shared.m_attack.m_attackAnimation)) continue;
AttackKind? kind = Classify(weapon.name.ToLower(), shared);
if (kind == null || profiles.ContainsKey(kind.Value)) continue;
Attack a = shared.m_attack;
Profile p = new Profile
{
Source = weapon.name,
Trigger = a.m_attackAnimation,
Damage = shared.m_damages,
Type = a.m_attackType,
Range = a.m_attackRange,
Height = a.m_attackHeight,
Angle = a.m_attackAngle,
PushForce = shared.m_attackForce,
ToolTier = shared.m_toolTier,
Shared = shared,
Attach = weapon.transform.Find("attach")?.gameObject,
};
profiles[kind.Value] = p;
Jotunn.Logger.LogInfo($"[Trol] True Form {kind.Value} <- '{p.Source}': trigger '{p.Trigger}', {p.Type}, " +
$"range {p.Range:0.0}, blunt {p.Damage.m_blunt:0} slash {p.Damage.m_slash:0} " +
$"chop {p.Damage.m_chop:0} pickaxe {p.Damage.m_pickaxe:0}.");
}
if (!profiles.ContainsKey(AttackKind.Punch))
{
Jotunn.Logger.LogWarning($"[Trol] '{Creature}' carries no punch; True Form left click will do nothing.");
}
}
private static AttackKind? Classify(string name, ItemDrop.ItemData.SharedData shared)
{
if (name.Contains("throw") || shared.m_attack.m_attackProjectile != null) return AttackKind.Throw;
if (name.Contains("log"))
{
return name.EndsWith("_v") || name.Contains("vertical") ? AttackKind.LogSwingV : AttackKind.LogSwingH;
}
if (name.Contains("slam") || shared.m_attack.m_attackType == Attack.AttackType.Area) return AttackKind.Slam;
if (name.Contains("punch")) return AttackKind.Punch;
return null;
}
/// <summary>
/// The owner's side of a remote replay: records the trigger just fired, so
/// RemoteTrolTrueFormAnimator plays it on every other client's copy.
/// </summary>
public static void PublishAttackTrigger(Player player, string trigger)
{
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
attackSeq++;
nview.GetZDO().Set(AttackTriggerKey, trigger + "#" + attackSeq);
}
/// <summary>
/// The damage a troll attack deals for this player right now: the troll's own numbers, times
/// Troll Attack Damage, times the same random Clubs factor a club would get.
/// </summary>
public static HitData.DamageTypes DamageFor(Player player, Profile profile)
{
HitData.DamageTypes damage = profile.Damage.Clone();
float factor = TrolConfig.TrueFormTrollDamageShare.Value * player.GetRandomSkillFactor(Skills.SkillType.Clubs);
damage.Modify(factor);
return damage;
}
// ─── Native attack loop, shut while the costume is on ────────────────
/// <summary>
/// Holds the troll still through its own attack clips, the way vanilla roots a creature in
/// mid-swing. SkeletonRiseControlsPatch's arrangement: the move direction is the first
/// argument of SetControls, bound by position.
/// </summary>
[HarmonyPatch(typeof(Player), "SetControls")]
public static class Trol_TrueFormHoldStill_Patch
{
public static void Prefix(Player __instance, ref Vector3 __0, ref bool jump, ref bool crouch, ref bool dodge)
{
if (__instance != Player.m_localPlayer || !LocalActive || !LocalAttacking) return;
__0 = Vector3.zero;
jump = false;
crouch = false;
dodge = false;
}
}
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Trol_TrueFormBlockNativeAttack_Patch
{
public static bool Prefix(Humanoid __instance)
{
return __instance != Player.m_localPlayer || !LocalActive;
}
}
/// <summary>Crossbow reload and draw live here; see Fenrir's BlockPlayerAttackInputPatch.</summary>
[HarmonyPatch(typeof(Player), "PlayerAttackInput")]
public static class Trol_TrueFormBlockAttackInput_Patch
{
public static bool Prefix(Player __instance)
{
return __instance != Player.m_localPlayer || !LocalActive;
}
}
/// <summary>
/// The troll's own clips call OnAttackTrigger at the moment a blow lands, and it arrives on
/// the player. It is the hit cue for TrolTrueFormBehavior, and it must go no further: let
/// through, it fires whatever attack the human still has in hand.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))]
public static class Trol_TrueFormAttackTrigger_Patch
{
public static bool Prefix(Humanoid __instance)
{
if (__instance != Player.m_localPlayer || !LocalActive) return true;
NotifyAttackTrigger();
return false;
}
}
}
}