diff --git a/JotunnModStub/AnimatorDump.cs b/JotunnModStub/AnimatorDump.cs new file mode 100644 index 0000000..edb5e40 --- /dev/null +++ b/JotunnModStub/AnimatorDump.cs @@ -0,0 +1,303 @@ +using System.Collections.Generic; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Reads out a creature's animator, because guessing at animation has cost this mod real time: + /// a howl that was looked for under three wrong names, a taunt animation nobody knew played, and + /// a sound prefab that killed the process when spawned on its own. + /// + /// WHAT UNITY LETS US SEE AT RUNTIME, and what it does not, because the line matters: + /// + /// Readable. Every parameter with its type. Every layer. Every CLIP in the controller with its + /// name and length, through RuntimeAnimatorController.animationClips - so a creature's whole + /// vocabulary can be listed without ever wearing it. And every AnimationEvent on every clip: + /// the instant, the method name it calls, and its parameters. That last one is where a sound + /// fired by an animation lives, which is the thing this was written to find. + /// + /// Not readable. The state machine. States and transitions live in AnimatorController, which is + /// an editor-only type, and GetCurrentAnimatorStateInfo hands back hashes with no names. States + /// can only be guessed and then confirmed: AnimatorStateInfo.IsName("Layer.Name") answers yes or + /// no, and Animator.Play takes a state name we can try and then verify by reading back which + /// clip actually started. + /// + /// So "catch the howl and trigger just that stretch" is possible, in this order: list the clips + /// here, find the one that looks like a howl, look at its events to see whether the sound is + /// wired into the animation, then Play the state and CrossFade back to idle at the point wanted. + /// Worth knowing before starting: if the sound is an animation event, playing the clip alone will + /// not make it, because events are dispatched to a component on the animated object and Valheim's + /// dispatcher is CharacterAnimEvent. The animation is the prize; the audio we already play + /// ourselves. + /// + public class DumpAnimCommand : ConsoleCommand + { + public override string Name => "dumpanim"; + + public override string Help => + "[DEBUG] dumpanim - lists a creature's animator parameters, layers, clips and " + + "every animation event on them. dumpanim live - logs which clip each animator under you " + + "starts playing, as it happens; run it again to stop."; + + public override void Run(string[] args) + { + if (args.Length == 0) + { + Console.instance.Print("dumpanim | dumpanim live"); + return; + } + + if (args[0].ToLower() == "live") + { + ToggleWatcher(); + return; + } + + DumpPrefab(args[0]); + } + + /// + /// Everything the controller of can play. Reads a prefab in + /// memory, so it needs no transformation and cannot disturb a live one. + /// + private static void DumpPrefab(string prefabName) + { + GameObject prefab = PrefabManager.Cache.GetPrefab(prefabName); + if (prefab == null) + { + Report($"[Anim] '{prefabName}' is not in the prefab cache."); + return; + } + + Animator[] animators = prefab.GetComponentsInChildren(true); + if (animators.Length == 0) + { + // Not a creature. Say what it is anyway: this is also how a sound prefab gets looked + // at without being spawned, which matters for the ones that cannot safely be spawned. + Report($"[Anim] '{prefabName}' has no Animator. Contents:"); + foreach (Transform t in prefab.GetComponentsInChildren(true)) + { + Jotunn.Logger.LogInfo($"[Anim] '{PathOf(t)}' [{ComponentsOf(t.gameObject)}]"); + DescribeAudio(t.gameObject); + } + return; + } + + Report($"[Anim] '{prefabName}': {animators.Length} animator(s)."); + + foreach (Animator animator in animators) + { + RuntimeAnimatorController controller = animator.runtimeAnimatorController; + Report($"[Anim] on '{PathOf(animator.transform)}' controller " + + $"'{(controller != null ? controller.name : "none")}'"); + + // What else lives on that object, because an animation event is delivered to THESE + // components and nowhere else. CharacterAnimEvent showing up here is the game's own + // receiver; a form that carries it is a form where vanilla is already handling - or + // already failing to handle - every event the clips fire. + Jotunn.Logger.LogInfo($"[Anim] receivers: [{ComponentsOf(animator.gameObject)}]"); + + if (controller == null) continue; + + foreach (AnimatorControllerParameter p in animator.parameters) + { + Jotunn.Logger.LogInfo($"[Anim] param {p.name} ({p.type})"); + } + + for (int i = 0; i < animator.layerCount; i++) + { + Jotunn.Logger.LogInfo($"[Anim] layer {i} '{animator.GetLayerName(i)}'"); + } + + AnimationClip[] clips = controller.animationClips; + Report($"[Anim] {clips.Length} clip(s):"); + + foreach (AnimationClip clip in clips) + { + if (clip == null) continue; + + AnimationEvent[] events = clip.events; + Jotunn.Logger.LogInfo( + $"[Anim] '{clip.name}' {clip.length:F2}s loop={clip.isLooping} " + + $"events={events.Length}"); + + foreach (AnimationEvent e in events) + { + // The object reference is the interesting one: a sound wired into an + // animation arrives here as the asset itself, name included. + string reference = e.objectReferenceParameter != null + ? $" ref='{e.objectReferenceParameter.name}' ({e.objectReferenceParameter.GetType().Name})" + : ""; + Jotunn.Logger.LogInfo( + $"[Anim] @{e.time:F2}s {e.functionName}(" + + $"string='{e.stringParameter}' float={e.floatParameter:F2} " + + $"int={e.intParameter}){reference}"); + } + } + } + } + + private static void ToggleWatcher() + { + if (Player.m_localPlayer == null) + { + Console.instance.Print("dumpanim live needs you to be in the world."); + return; + } + + AnimatorWatcher existing = Player.m_localPlayer.GetComponent(); + if (existing != null) + { + Object.Destroy(existing); + Report("[Anim] live watch off."); + return; + } + + Player.m_localPlayer.gameObject.AddComponent(); + Report("[Anim] live watch on: every clip change under you, as it happens."); + } + + /// + /// Why a sound prefab is or is not audible when it is simply instantiated. + /// + /// The AudioSource settings say whether anything starts by itself, and ZSFX's own fields say + /// what it would play if asked - it keeps a LIST of clips and chooses at play time, so a + /// prefab whose AudioSource has no clip is normal rather than broken. Read through reflection + /// because these are the game's private serialized fields. + /// + private static void DescribeAudio(GameObject go) + { + AudioSource audio = go.GetComponent(); + if (audio != null) + { + Jotunn.Logger.LogInfo( + $"[Anim] AudioSource playOnAwake={audio.playOnAwake} " + + $"clip='{(audio.clip != null ? audio.clip.name : "none")}' " + + $"volume={audio.volume:F2} spatialBlend={audio.spatialBlend:F2} " + + $"range={audio.minDistance:F1}-{audio.maxDistance:F1} loop={audio.loop} " + + $"mixer='{(audio.outputAudioMixerGroup != null ? audio.outputAudioMixerGroup.name : "none")}'"); + } + + foreach (Component comp in go.GetComponents()) + { + if (comp == null || comp.GetType().Name != "ZSFX") continue; + + List fields = new List(); + foreach (System.Reflection.FieldInfo f in comp.GetType().GetFields( + System.Reflection.BindingFlags.Instance | + System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.NonPublic)) + { + object value = f.GetValue(comp); + System.Array array = value as System.Array; + if (array == null) + { + fields.Add($"{f.Name}={value}"); + continue; + } + + // The elements, not just the count. m_audioClips is where a sound's actual clips + // live, and whether they are AudioClips or unloaded soft references is the whole + // question when a sound spawns and stays silent. + List elements = new List(); + for (int e = 0; e < array.Length && e < 4; e++) + { + object item = array.GetValue(e); + Object asObject = item as Object; + elements.Add(item == null + ? "null" + : $"{item.GetType().Name}:'{(asObject != null ? asObject.name : item.ToString())}'"); + } + fields.Add($"{f.Name}[{array.Length}]={{{string.Join(", ", elements.ToArray())}}}"); + } + + Jotunn.Logger.LogInfo($"[Anim] ZSFX {string.Join(" ", fields.ToArray())}"); + Jotunn.Logger.LogInfo( + $"[Anim] ZSFX methods: {string.Join(", ", MethodNamesOf(comp))}"); + } + } + + private static string[] MethodNamesOf(Component comp) + { + List names = new List(); + foreach (System.Reflection.MethodInfo m in comp.GetType().GetMethods( + System.Reflection.BindingFlags.Instance | + System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.DeclaredOnly)) + { + names.Add(m.Name + "(" + m.GetParameters().Length + ")"); + } + return names.ToArray(); + } + + /// The component type names on one object, Transform left out as noise. + private static string ComponentsOf(GameObject go) + { + List names = new List(); + foreach (Component comp in go.GetComponents()) + { + if (comp != null && !(comp is Transform)) names.Add(comp.GetType().Name); + } + return string.Join(", ", names.ToArray()); + } + + private static string PathOf(Transform t) + { + string path = t.name; + for (Transform p = t.parent; p != null; p = p.parent) path = p.name + "/" + path; + return path; + } + + /// To the log and to the console both, since one of the two is always the wrong one. + private static void Report(string line) + { + Jotunn.Logger.LogInfo(line); + if (Console.instance != null) Console.instance.Print(line); + } + + /// + /// Watches every animator under the player and says when one starts a different clip. + /// + /// Only the change is logged, not the state: an animator asked every frame would fill the log + /// with the idle it is already playing. The heaviest clip is the one reported, because during + /// a transition two are live at once and the heavier one is the one being watched on screen. + /// + private class AnimatorWatcher : MonoBehaviour + { + private readonly Dictionary last = new Dictionary(); + + private void Update() + { + foreach (Animator animator in GetComponentsInChildren(true)) + { + if (animator == null || animator.runtimeAnimatorController == null) continue; + + AnimatorClipInfo[] playing = animator.GetCurrentAnimatorClipInfo(0); + if (playing.Length == 0) continue; + + AnimationClip heaviest = null; + float weight = -1f; + foreach (AnimatorClipInfo info in playing) + { + if (info.clip != null && info.weight > weight) + { + heaviest = info.clip; + weight = info.weight; + } + } + if (heaviest == null) continue; + + string previous; + if (last.TryGetValue(animator, out previous) && previous == heaviest.name) continue; + + last[animator] = heaviest.name; + Jotunn.Logger.LogInfo( + $"[Anim] live: '{PathOf(animator.transform)}' -> '{heaviest.name}' " + + $"{heaviest.length:F2}s weight={weight:F2} events={heaviest.events.Length}"); + } + } + } + } +} diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 0235ed9..c703e24 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -79,6 +79,7 @@ namespace RacesOfValheim CommandManager.Instance.AddConsoleCommand(new FenrirPackSpawnCommand()); CommandManager.Instance.AddConsoleCommand(new DumpPotionsCommand()); CommandManager.Instance.AddConsoleCommand(new ListPrefabsCommand()); + CommandManager.Instance.AddConsoleCommand(new DumpAnimCommand()); } ///