RacesOfValheim/JotunnModStub/Skeleton/SkeletonRise.cs
kanym 1848725f2a fix(skeleton): rise on resurrect, truce for bound troops, pile and sentry on floors
The Yagluth auto-resurrect now plays the crypt rise. The player rig has no
rise state, so the body is hidden and the skeleton model is worn for the
length of the clip with "wakeup" set; the start time goes on the ZDO so
other clients play it too. The player takes no damage and does not move
until it is out.

Wild faction mobs left the player alone but attacked the player's thralls,
which are tamed and so in the Players faction. IsEnemy now gives a thrall
the same truce through its m_commandingRace, broken by a grudge against
any player. Covers every race with thralls.

The Bound Bone Pile and the Bound Sentry seed drop m_groundPiece and
m_groundOnly, so both can be built on floors and foundations.
2026-10-07 04:11:08 +02:00

278 lines
12 KiB
C#

using System;
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
using Object = UnityEngine.Object;
namespace RacesOfValheim
{
/// <summary>
/// The Skeleton's auto-resurrection, played as the crypt rise: the body climbs out of the ground
/// instead of simply staying on its feet.
///
/// The player cannot play that clip itself. A Skeleton player is the human rig wearing a
/// skeleton's meshes (see VisEquipment_UpdateVisuals_Patch), and the human controller has no
/// rise state - "wakeup" lives in the skeleton creature's own controller. So for the few seconds
/// of the rise the player's Visual is hidden and a costume is worn in its place: the creature's
/// animated model, stripped down to renderers and its Animator, with the same "wakeup" bool set
/// that vanilla's CreatureSpawner sets on a Spawner_Skeleton_rise skeleton.
///
/// The start time goes on the ZDO, so every client that can see this player plays the same rise.
/// While it runs the local player takes no damage and does not move: they are half in the ground.
/// </summary>
public static class SkeletonRise
{
public const string ZdoKey = "RoV_skelRiseAt";
// How long after the start a client that only just noticed the key still bothers to play it.
// A player who walks into view a minute later should not see a resurrection replayed.
private const float RemoteLateStartSeconds = 2f;
private const float FallbackSeconds = 3f;
private const float MaxSeconds = 6f;
// Clips that look like a rise, by name. Matched loosely and logged once, so a wrong pick
// shows up in the log with every clip the controller actually has.
private static readonly string[] RiseClipWords = { "wake", "rise", "spawn", "getup", "emerge" };
private static readonly Dictionary<string, GameObject> templates = new Dictionary<string, GameObject>();
private static readonly Dictionary<string, float> riseSeconds = new Dictionary<string, float>();
public static bool IsRising(Player player)
{
if (player == null) return false;
SkeletonRiseCostume costume = player.GetComponent<SkeletonRiseCostume>();
return costume != null && costume.IsPlaying;
}
/// <summary>Starts the rise for the local player and tells everyone else.</summary>
public static void Begin(Player player)
{
if (player == null || ZNet.instance == null) return;
long ticks = ZNet.instance.GetTime().Ticks;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set(ZdoKey, ticks);
Play(player, ticks);
}
/// <summary>For a remote player: plays a rise this client has not played yet, if it is fresh.</summary>
public static void CheckRemote(Player player)
{
if (player == null || ZNet.instance == null) return;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return;
long ticks = nview.GetZDO().GetLong(ZdoKey, 0L);
if (ticks == 0L) return;
SkeletonRiseCostume costume = player.GetComponent<SkeletonRiseCostume>();
if (costume != null && costume.StartedTicks == ticks) return;
double age = (ZNet.instance.GetTime() - new DateTime(ticks)).TotalSeconds;
if (age < 0 || age > RemoteLateStartSeconds)
{
// Remember it anyway, so the age is not worked out again every frame.
if (costume == null) costume = player.gameObject.AddComponent<SkeletonRiseCostume>();
costume.StartedTicks = ticks;
return;
}
Play(player, ticks);
}
private static void Play(Player player, long ticks)
{
string model = SkeletonVisuals.GetModel(player, SkeletonVisuals.GetProgressionState(player));
GameObject template = GetTemplate(model);
if (template == null) return;
SkeletonRiseCostume costume = player.GetComponent<SkeletonRiseCostume>()
?? player.gameObject.AddComponent<SkeletonRiseCostume>();
costume.StartedTicks = ticks;
costume.Play(template, riseSeconds.TryGetValue(model, out float seconds) ? seconds : FallbackSeconds);
}
/// <summary>
/// The creature's animated model, stripped once per model name. Built into an inactive
/// holder, so nothing on the copy wakes before the strip - the rule ModelBorrow exists for.
/// </summary>
private static GameObject GetTemplate(string modelPrefab)
{
if (templates.TryGetValue(modelPrefab, out GameObject cached)) return cached;
templates[modelPrefab] = null;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(modelPrefab);
Animator sourceAnim = source != null ? source.GetComponentInChildren<Animator>(true) : null;
if (sourceAnim == null)
{
Jotunn.Logger.LogWarning($"[Skeleton] Rise: no animated model on '{modelPrefab}'; the resurrection plays without the rise.");
return null;
}
GameObject holder = new GameObject("SkeletonRiseTemplate_" + modelPrefab);
Object.DontDestroyOnLoad(holder);
holder.SetActive(false); // BEFORE Instantiate: nothing on the copy gets to Awake.
GameObject copy = Object.Instantiate(sourceAnim.gameObject, holder.transform);
copy.name = "model";
copy.transform.localPosition = sourceAnim.transform.localPosition;
copy.transform.localRotation = sourceAnim.transform.localRotation;
copy.transform.localScale = sourceAnim.transform.localScale;
// Everything that is not a Renderer, a Transform or the Animator. Animator is a Behaviour,
// not a MonoBehaviour, so the first loop never touches it.
foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour != null) Object.DestroyImmediate(behaviour);
}
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);
}
riseSeconds[modelPrefab] = MeasureRise(sourceAnim, modelPrefab);
templates[modelPrefab] = copy;
return copy;
}
private static float MeasureRise(Animator animator, string modelPrefab)
{
RuntimeAnimatorController controller = animator.runtimeAnimatorController;
if (controller == null) return FallbackSeconds;
AnimationClip best = null;
List<string> names = new List<string>();
foreach (AnimationClip clip in controller.animationClips)
{
if (clip == null) continue;
names.Add($"{clip.name} ({clip.length:0.00}s)");
string lower = clip.name.ToLower();
foreach (string word in RiseClipWords)
{
if (!lower.Contains(word)) continue;
if (best == null || clip.length > best.length) best = clip;
break;
}
}
float seconds = best != null ? Mathf.Clamp(best.length, 1f, MaxSeconds) : FallbackSeconds;
Jotunn.Logger.LogInfo(
$"[Skeleton] Rise on '{modelPrefab}': clip '{(best != null ? best.name : "none, fallback")}', {seconds:0.00}s. " +
$"Clips: {string.Join(", ", names.ToArray())}");
return seconds;
}
}
/// <summary>The worn costume for one rise. Lives on the player and is reused for the next one.</summary>
public class SkeletonRiseCostume : MonoBehaviour
{
private const string HiderContext = "skeleton-rise";
public long StartedTicks;
private Player m_player;
private GameObject m_model;
private float m_endsAt;
public bool IsPlaying => m_model != null;
public void Play(GameObject template, float seconds)
{
m_player = GetComponent<Player>();
End();
m_model = Instantiate(template, transform);
m_model.name = "SkeletonRiseCostume";
m_model.transform.localPosition = template.transform.localPosition;
m_model.transform.localRotation = template.transform.localRotation;
m_model.transform.localScale = template.transform.localScale;
Animator anim = m_model.GetComponentInChildren<Animator>();
if (anim != null)
{
// Same settings the other borrowed costumes use: the clip must not walk the model off
// its wearer, its events have no receivers left, and it keeps animating close to the
// camera.
anim.applyRootMotion = false;
anim.fireEvents = false;
anim.cullingMode = AnimatorCullingMode.AlwaysAnimate;
bool hasWakeup = false;
foreach (AnimatorControllerParameter param in anim.parameters)
{
if (param.type == AnimatorControllerParameterType.Bool && param.name == "wakeup") hasWakeup = true;
}
if (hasWakeup)
{
anim.SetBool("wakeup", true);
// Settle into the rise now, so the first rendered frame is not a standing skeleton.
anim.Update(0f);
anim.Update(0f);
}
else
{
Jotunn.Logger.LogWarning("[Skeleton] Rise: the model's Animator has no 'wakeup' bool; it will stand instead of rising.");
}
}
PlayerVisualHider.Hide(transform.Find("Visual"), HiderContext);
m_endsAt = Time.time + seconds;
}
private void Update()
{
if (m_model == null) return;
if (Time.time >= m_endsAt || m_player == null || m_player.IsDead()) End();
}
private void End()
{
if (m_model == null) return;
// Switched off first: Destroy waits for the end of the frame, and nothing on the costume
// should run in between.
m_model.SetActive(false);
Destroy(m_model);
m_model = null;
PlayerVisualHider.Show(transform.Find("Visual"), HiderContext);
}
private void OnDestroy() => End();
}
/// <summary>
/// Holds the local player still while they climb out. The movement direction is bound by
/// position, not name: it is the first argument of Player.SetControls.
/// </summary>
[HarmonyPatch(typeof(Player), "SetControls")]
public static class SkeletonRiseControlsPatch
{
public static void Prefix(Player __instance, ref Vector3 __0,
ref bool attack, ref bool attackHold,
ref bool secondaryAttack, ref bool secondaryAttackHold,
ref bool jump, ref bool crouch, ref bool dodge)
{
if (__instance != Player.m_localPlayer || !SkeletonRise.IsRising(__instance)) return;
__0 = Vector3.zero;
attack = false;
attackHold = false;
secondaryAttack = false;
secondaryAttackHold = false;
jump = false;
crouch = false;
dodge = false;
}
}
}