RacesOfValheim/JotunnModStub/WarVulture/WarVultureVisual.cs
2026-08-09 21:54:56 +02:00

376 lines
17 KiB
C#

using UnityEngine;
using Jotunn.Managers;
namespace RacesOfValheim
{
/// <summary>
/// The bird's body: built dead once, then copied.
///
/// WHY IT IS BUILT AT REGISTRATION AND NOT AT THE SUMMON. The first version borrowed the model
/// the way ModelBorrow does it - instantiate into an inactive holder, then DestroyImmediate
/// everything that is not a renderer. That is correct at registration time and wrong at summon
/// time, and the game says so out loud:
///
/// Destroying components immediately is not permitted during physics trigger/contact,
/// animation event callbacks, rendering callbacks or OnValidate.
///
/// The summon runs from Attack.OnAttackTrigger, which the game calls from CharacterAnimEvent -
/// an animation event callback. Every DestroyImmediate was refused, the model kept its
/// Character, its MonsterAI and its ZNetView, and the moment the holder was switched on Awake
/// ran and a real Ashlands predator was born under the player. A live rigidbody ignores its
/// parent transform, so it flew off. Eleven refusal lines sat in the log directly above the
/// "Borrowed 'Volture'" line, which is exactly how it was found.
///
/// So: the stripping happens once, during CreateAllModAssets, where DestroyImmediate is legal.
/// What is kept is a TEMPLATE - an inactive, script-free carcass held in DontDestroyOnLoad -
/// and a summon is a plain Instantiate of it. Instantiate is allowed in any context.
///
/// And it is CHECKED, not assumed. If a single MonoBehaviour survives the strip, the template
/// is thrown away and the item refuses to summon. A bird that does not appear is a bug report;
/// a bird that appears with an AI is a predator in the player's world with a saved ZDO.
/// </summary>
public static class WarVultureVisual
{
private const string SourcePrefab = "Volture";
private const string Label = "WarVulture";
// The three parameters DrakeFormBehavior drives, which is the only animated borrowed
// creature in this mod known to look right.
private const string FlyingParam = "flying";
private const string GroundParam = "onGround";
private const string SpeedParam = "forward_speed";
private static GameObject template;
private static float templateSize = 1f;
public static bool Ready => template != null;
// ---------------------------------------------------------------- the template
/// <summary>
/// Called once from WarVultureItem.Register, i.e. from CreateAllModAssets, i.e. from a
/// context where components may be destroyed immediately.
/// </summary>
public static void BuildTemplate()
{
if (template != null) return;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SourcePrefab);
if (source == null)
{
Jotunn.Logger.LogWarning($"[{Label}] No '{SourcePrefab}' prefab to copy; the mount will refuse " +
"to summon rather than put an invisible rider in the sky.");
return;
}
// Inactive BEFORE the Instantiate - the one line that keeps Awake from running on a
// live predator. Everything else here depends on it.
GameObject root = new GameObject("WarVultureTemplate");
root.SetActive(false);
Object.DontDestroyOnLoad(root);
GameObject copy = Object.Instantiate(source, root.transform);
copy.name = "VoltureModel";
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.transform.localScale = Vector3.one;
int refused = StripToRenderers(copy);
int alive = CountBehaviours(copy);
if (alive > 0)
{
Jotunn.Logger.LogError($"[{Label}] {alive} script(s) survived the strip on '{SourcePrefab}' " +
$"({refused} destroy calls were refused). The template is being thrown " +
"away and the War Vulture will not summon - a half-stripped creature " +
"prefab is a live animal, not a model.");
Object.DestroyImmediate(root);
return;
}
PrepareAnimator(copy);
templateSize = Mathf.Max(0.01f, LargestDimension(copy));
template = copy;
}
/// <summary>
/// Everything that is not geometry or animation, removed in passes.
///
/// Passes rather than one sweep because Unity refuses to destroy a component another
/// component still requires, and the refusal is silent as far as the caller is concerned -
/// it logs and moves on. Repeating until a pass changes nothing lets a dependency chain
/// unwind in whatever order it needs to.
///
/// Returns how many destroy calls were refused on the last pass, purely so the failure
/// above can say something useful.
/// </summary>
private static int StripToRenderers(GameObject copy)
{
int stubborn = 0;
for (int pass = 0; pass < 6; pass++)
{
bool destroyedSomething = false;
stubborn = 0;
foreach (Component component in copy.GetComponentsInChildren<Component>(true))
{
if (component == null) continue;
if (IsKept(component)) continue;
Object.DestroyImmediate(component);
if (component == null) destroyedSomething = true;
else stubborn++;
}
if (!destroyedSomething) break;
}
return stubborn;
}
/// <summary>
/// The whitelist. Anything not on it goes - colliders, rigidbodies, ZNetView, Character,
/// MonsterAI, the lot. Keeping a list of what to KEEP rather than a list of what to remove
/// is the difference between a model and an animal: a new component in a future Valheim
/// patch is removed by default instead of surviving by omission.
///
/// The two MESH renderers by name rather than Renderer as a family, which looks like
/// pedantry and is not: ParticleSystemRenderer is a Renderer, and "keep every Renderer" is
/// how the trophy in the player's hand ended up carrying the sparkle vanilla puts on
/// dropped loot. Meshes and the animator that poses them - nothing else.
/// </summary>
private static bool IsKept(Component component)
{
return component is Transform
|| component is MeshFilter
|| component is MeshRenderer
|| component is SkinnedMeshRenderer
|| component is Animator
|| component is LODGroup;
}
private static int CountBehaviours(GameObject copy)
{
int alive = 0;
foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour != null) alive++;
}
return alive;
}
/// <summary>
/// Three settings, each preventing one specific failure rather than tidying anything.
///
/// applyRootMotion: clips authored to walk a creature through the world would walk the
/// model out from under its rider.
///
/// cullingMode: the default stops animating when no renderer is on screen, and this bird
/// lives half off the bottom of the screen - a frozen mid-flap reads as a bug.
///
/// fireEvents: the flight clips carry animation events aimed at CharacterAnimEvent, which
/// has just been stripped off. Left on, every wingbeat would log "has no receiver".
/// </summary>
private static void PrepareAnimator(GameObject copy)
{
Animator animator = copy.GetComponentInChildren<Animator>(true);
if (animator == null)
{
Jotunn.Logger.LogWarning($"[{Label}] The stripped '{SourcePrefab}' has no Animator, so the bird " +
"will hang in its bind pose - wings out, legs straight.");
return;
}
animator.applyRootMotion = false;
animator.cullingMode = AnimatorCullingMode.AlwaysAnimate;
animator.fireEvents = false;
animator.enabled = true;
}
// ---------------------------------------------------------------- summoning a copy
/// <summary>
/// Hangs a copy of the template under a rider and returns the rig that keeps it there.
/// Null when the template could not be built, which the caller must treat as "do not
/// summon" rather than "summon an invisible bird".
/// </summary>
public static WarVultureRig Spawn(Transform rider, string holderName)
{
if (template == null || rider == null) return null;
GameObject holder = new GameObject(holderName);
holder.transform.SetParent(rider, false);
holder.transform.localPosition = Vector3.zero;
holder.transform.localRotation = Quaternion.identity;
GameObject model = Object.Instantiate(template, holder.transform);
model.name = "model";
model.transform.localPosition = Vector3.zero;
model.transform.localRotation = Quaternion.identity;
model.transform.localScale = Vector3.one * (WarVultureConfig.MountSize.Value / templateSize);
model.SetActive(true);
WarVultureRig rig = holder.AddComponent<WarVultureRig>();
rig.Bind(rider, model);
return rig;
}
// ---------------------------------------------------------------- animation
/// <summary>
/// One frame of flight, told to the animator. Any parameter this controller does not have
/// is skipped, so a Valheim animator rename costs a stiff-looking bird rather than a wall
/// of errors every frame.
/// </summary>
public static void Drive(Animator animator, float forwardSpeed)
{
if (animator == null || animator.runtimeAnimatorController == null) return;
if (Has(animator, FlyingParam, AnimatorControllerParameterType.Bool)) animator.SetBool(FlyingParam, true);
if (Has(animator, GroundParam, AnimatorControllerParameterType.Bool)) animator.SetBool(GroundParam, false);
if (Has(animator, SpeedParam, AnimatorControllerParameterType.Float)) animator.SetFloat(SpeedParam, forwardSpeed);
}
private static bool Has(Animator animator, string name, AnimatorControllerParameterType type)
{
foreach (AnimatorControllerParameter parameter in animator.parameters)
{
if (parameter.type == type && parameter.name == name) return true;
}
return false;
}
// ---------------------------------------------------------------- the seat bone
/// <summary>
/// The bone the rider sits on.
///
/// A bone rather than an offset in metres, because that is the difference between sitting
/// on the bird and hovering above it: the back moves with every wingbeat, and a fixed
/// offset can only ever be right on one frame of the animation.
///
/// The name is guessed from a priority list and can be overridden in config, because the
/// rig's bone names are not knowable from outside the game. The automatic pick was the right
/// one in play, so the startup dump that found it has been retired.
/// </summary>
public static Transform FindSeatBone(GameObject model)
{
if (model == null) return null;
Transform[] bones = model.GetComponentsInChildren<Transform>(true);
string wanted = WarVultureConfig.SeatBone.Value;
if (!string.IsNullOrEmpty(wanted))
{
Transform named = Match(bones, wanted);
if (named != null) return named;
Jotunn.Logger.LogWarning($"[{Label}] No bone matching '{wanted}' on the vulture; falling back " +
"to the automatic pick. The bone list is in the log from startup.");
}
// Deliberately in this order: the back of a bird is its spine and chest, and the hips
// and root are last-ditch so that SOMETHING is anchored rather than nothing.
foreach (string candidate in new[] { "spine", "chest", "back", "torso", "body", "pelvis", "hip", "root" })
{
Transform found = Match(bones, candidate);
if (found != null) return found;
}
return null;
}
/// <summary>
/// Last match rather than first, on purpose: rigs number their spines outward from the
/// hips, so the last "spine" is the one furthest along the back - which is where a saddle
/// goes, not where the tail joins.
/// </summary>
private static Transform Match(Transform[] bones, string needle)
{
Transform best = null;
foreach (Transform bone in bones)
{
if (bone.name.IndexOf(needle, System.StringComparison.OrdinalIgnoreCase) >= 0) best = bone;
}
return best;
}
// ---------------------------------------------------------------- measuring
private static float LargestDimension(GameObject model)
{
bool any = false;
Bounds bounds = new Bounds();
foreach (Renderer renderer in model.GetComponentsInChildren<Renderer>(true))
{
Mesh mesh = renderer is SkinnedMeshRenderer skinned
? skinned.sharedMesh
: renderer.GetComponent<MeshFilter>()?.sharedMesh;
if (mesh == null) continue;
Bounds local = mesh.bounds;
Matrix4x4 toModel = model.transform.worldToLocalMatrix * renderer.transform.localToWorldMatrix;
for (int corner = 0; corner < 8; corner++)
{
Vector3 point = toModel.MultiplyPoint3x4(local.center + new Vector3(
(corner & 1) == 0 ? -local.extents.x : local.extents.x,
(corner & 2) == 0 ? -local.extents.y : local.extents.y,
(corner & 4) == 0 ? -local.extents.z : local.extents.z));
if (!any) { bounds = new Bounds(point, Vector3.zero); any = true; }
else bounds.Encapsulate(point);
}
}
return any ? Mathf.Max(bounds.size.x, Mathf.Max(bounds.size.y, bounds.size.z)) : 1f;
}
}
/// <summary>
/// Keeps the bird under its rider, one bone at a time.
///
/// In LateUpdate, after the animator has posed the skeleton for this frame, the whole model is
/// slid so that the seat bone lands exactly on the rider's own origin. That is what "sitting on
/// the bird's back" means as a piece of code, and it is why there is no height offset anywhere
/// in this feature any more: the back tells us where it is, every frame, including while it
/// rises and falls with the wingbeat.
///
/// Shared by the rider's own copy and by the copy other players see, so the bird cannot sit in
/// two different places depending on who is looking.
/// </summary>
public class WarVultureRig : MonoBehaviour
{
private Transform rider;
private Transform model;
private Transform seatBone;
private Animator animator;
public void Bind(Transform rider, GameObject model)
{
this.rider = rider;
this.model = model.transform;
seatBone = WarVultureVisual.FindSeatBone(model);
animator = model.GetComponentInChildren<Animator>(true);
}
public void Drive(float forwardSpeed)
{
WarVultureVisual.Drive(animator, forwardSpeed);
}
private void LateUpdate()
{
if (rider == null || model == null) return;
Vector3 seat = rider.position + rider.rotation * new Vector3(
0f, WarVultureConfig.SeatNudgeY.Value, WarVultureConfig.SeatNudgeZ.Value);
if (seatBone != null) model.position += seat - seatBone.position;
else model.position = seat;
}
}
}