diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index f412620..3d33ddf 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -48,6 +48,12 @@ namespace RacesOfValheim // drives the creature's own sleep through it, and not every creature has one. private Animator sleepChecked; private bool hasSleeping; + private int sleepState; + private bool wasSitting; + // Read off ulv_animator with scripts/dump_controller.py: the entry state "check sleeping" goes + // to Sleep only at start-up, and Movement has no way back into it. "Base Layer.Sleep" is the + // real path; the short name stays as a fallback for another creature built the same way. + private static readonly string[] SleepStateNames = { "Base Layer.Sleep", "Sleep" }; private static readonly System.Collections.Generic.HashSet sleepLogged = new System.Collections.Generic.HashSet(); /// Copies the movement parameters, and says whether the form counts as grounded. @@ -66,8 +72,15 @@ namespace RacesOfValheim // sneaking in a form slid across the ground in the idle pose. Crouched, the player moves // at sneaking speed, and the creature's controller picks its walk for a speed that low: // the sneak a player asked for, from animations the creature already has. - try { form.SetFloat("forward_speed", grounded ? playerAnim.GetFloat("forward_speed") : 0f); } catch {} - try { form.SetFloat("sideway_speed", grounded ? playerAnim.GetFloat("sideway_speed") : 0f); } catch {} + // + // Sitting reads as still too. The seated player's own Animator keeps a forward_speed that + // is not zero, and passed through it kept the Ulv in its Walk clip - on the spot, and out + // of reach of its Sleep state, which only leaves from idle. Seen in the log: sitting, + // sleeping=true, clip 'Walk'. + bool sitting = IsSitting(player); + bool still = !grounded || sitting; + try { form.SetFloat("forward_speed", still ? 0f : playerAnim.GetFloat("forward_speed")); } catch {} + try { form.SetFloat("sideway_speed", still ? 0f : playerAnim.GetFloat("sideway_speed")); } catch {} // Sitting puts the creature to sleep, on the "sleeping" bool its own MonsterAI uses - the // Ulv curls up. IsSitting reads the animator's state, which is replicated, so it is right @@ -80,18 +93,111 @@ namespace RacesOfValheim { if (p.type == AnimatorControllerParameterType.Bool && p.name == "sleeping") { hasSleeping = true; break; } } + + // The state's name is not readable at runtime, only testable - but it is readable offline, + // see SleepStateNames. + sleepState = 0; + string found = "none"; + if (hasSleeping) + { + foreach (string candidate in SleepStateNames) + { + int hash = Animator.StringToHash(candidate); + if (!form.HasState(0, hash)) continue; + sleepState = hash; + found = candidate; + break; + } + } string controller = form.runtimeAnimatorController != null ? form.runtimeAnimatorController.name : form.name; if (sleepLogged.Add(controller)) { Jotunn.Logger.LogInfo($"[FenrirForm] '{controller}' {(hasSleeping ? "has" : "has no")} sleeping animation; " + - (hasSleeping ? "sitting puts it to sleep." : "sitting keeps it idle.")); + (hasSleeping ? $"sitting puts it to sleep (state '{found}')." : "sitting keeps it idle.")); } } - if (hasSleeping) form.SetBool("sleeping", IsSitting(player)); + if (hasSleeping) + { + form.SetBool("sleeping", sitting); + + // The bool alone never put the Ulv to sleep. A vanilla Ulv is BORN asleep: its + // controller enters Sleep from the start and only knows the way out (Sleep, then + // 'Sleep to Idle' once the bool drops). Nothing leads from Idle back into Sleep, so + // the state is entered by hand when the player sits; standing up drops the bool and + // the controller's own wake-up plays. + if (sitting && !wasSitting && sleepState != 0) form.CrossFadeInFixedTime(sleepState, 0.4f, 0); + } + wasSitting = sitting; + + PlaceOnChair(form, player); return grounded; } + // How far in front of the seat a creature on a chair settles, in metres. + private const float ChairForward = 0.5f; + private static readonly int ChairGroundMask = LayerMask.GetMask("Default", "static_solid", "terrain", "piece", "vehicle"); + private static readonly RaycastHit[] chairHits = new RaycastHit[16]; + private Transform placedRoot; + + /// + /// On a chair the player sits on the seat itself, and a creature there stood inside the chair, + /// at seat height. It goes half a metre in front of the seat instead, standing on whatever is + /// under that point. Moves the form's own root (the child of the player), never the player. + /// The sit key is left alone: the player is on the ground already. + /// + private void PlaceOnChair(Animator form, Player player) + { + Transform root = RootUnder(form.transform, player != null ? player.transform : null); + if (root == null) return; + + bool onChair = player.IsSitting(); + if (!onChair) + { + if (placedRoot == root && root.localPosition != Vector3.zero) root.localPosition = Vector3.zero; + return; + } + placedRoot = root; + + Transform body = player.transform; + Piece seat = SeatUnder(body.position); + Vector3 target = body.position + body.forward * ChairForward; + + float groundY = target.y; + int count = Physics.RaycastNonAlloc(target + Vector3.up * 1.5f, Vector3.down, chairHits, 4f, ChairGroundMask); + float best = float.MaxValue; + for (int i = 0; i < count; i++) + { + Collider c = chairHits[i].collider; + if (c == null || c.transform.IsChildOf(body)) continue; + if (seat != null && c.GetComponentInParent() == seat) continue; + if (chairHits[i].distance < best) { best = chairHits[i].distance; groundY = chairHits[i].point.y; } + } + + root.localPosition = body.InverseTransformPoint(new Vector3(target.x, groundY, target.z)); + } + + /// The chair or bench the player sits on: the first piece straight under them. + private static Piece SeatUnder(Vector3 position) + { + int count = Physics.RaycastNonAlloc(position + Vector3.up * 0.3f, Vector3.down, chairHits, 1.5f, ChairGroundMask); + Piece seat = null; + float best = float.MaxValue; + for (int i = 0; i < count; i++) + { + Piece piece = chairHits[i].collider != null ? chairHits[i].collider.GetComponentInParent() : null; + if (piece != null && chairHits[i].distance < best) { best = chairHits[i].distance; seat = piece; } + } + return seat; + } + + private static Transform RootUnder(Transform t, Transform player) + { + if (player == null) return null; + while (t != null && t.parent != player) t = t.parent; + return t; + } + /// /// The sit key, or a chair. The sit key is an EMOTE, not the "sitting" animator tag that /// Humanoid.IsSitting asks about - that tag belongs to chairs and benches - so IsSitting alone diff --git a/scripts/dump_controller.py b/scripts/dump_controller.py new file mode 100644 index 0000000..07b9274 --- /dev/null +++ b/scripts/dump_controller.py @@ -0,0 +1,105 @@ +r"""Dump a Unity AnimatorController's parameters, states and transitions from Valheim's own files. + +Reads the game's asset files offline, so animator state and parameter names are read, not guessed. + +Setup, once (UnityPy into a folder of your choice, not into the repo): + python -m pip install --target C:\path o\pylib UnityPy + +Usage (Windows paths: a Git Bash "/c/..." path does not resolve for a Windows Python): + python -I scripts/dump_controller.py C:\path o\pylib " alheim_Data" ulv_animator wolf_animator + +Pass valheim_Data to search everything (slow, a few minutes), or a single bundle file to read +only that one. Creature animators live in valheim_Data\StreamingAssets\SoftRef\Bundles; the +Fenrir forms' four (wolf, ulv, fenring, fenring_cultist) are all in bundle c4210710 as of 1.0.20. +A controller's name is the one dumpanim prints ("controller 'ulv_animator'"). +""" +import os, sys, json + +sys.path.insert(0, sys.argv[1]) +import UnityPy # noqa: E402 + +data_dir = sys.argv[2] +wanted = set(sys.argv[3:]) + +candidates = [data_dir] if os.path.isfile(data_dir) else [] +for root, _, files in ([] if os.path.isfile(data_dir) else os.walk(data_dir)): + for f in files: + p = os.path.join(root, f) + if f.endswith(('.resS', '.resource', '.manifest', '.json', '.dll', '.csv', '.txt', '.info', '.config')): + continue + if os.path.getsize(p) < 1024: + continue + candidates.append(p) + +found = {} +for path in candidates: + try: + env = UnityPy.load(path) + except Exception: + continue + for obj in env.objects: + if obj.type.name != 'AnimatorController': + continue + try: + name = obj.peek_name() + except Exception: + name = None + if name is None: + try: + name = obj.read().m_Name + except Exception: + continue + if name not in wanted or name in found: + continue + tree = obj.read_typetree() + found[name] = (path, tree) + if len(found) == len(wanted): + break + +for name, (path, tree) in found.items(): + print(f'=== {name} ({os.path.basename(path)})') + tos = {int(k): v for k, v in tree.get('m_TOS', [])} + print('m_TOS (hash -> name):') + for h, v in sorted(tos.items(), key=lambda kv: kv[1]): + print(f' {h:>12} {v}') + + ctrl = tree.get('m_Controller', {}) + params = ctrl.get('m_Values', {}).get('data', {}).get('m_ValueArray', []) + print('parameters:') + for p in params: + print(f" {tos.get(p.get('m_ID'), p.get('m_ID'))} type={p.get('m_Type')}") + + for sm_i, sm in enumerate(ctrl.get('m_StateMachineArray', [])): + sm = sm.get('data', sm) + states = sm.get('m_StateConstantArray', []) + print(f'state machine {sm_i}: {len(states)} states, default index {sm.get("m_DefaultState")}') + any_tr = sm.get('m_AnyStateTransitionConstantArray', []) + + def describe(tr): + tr = tr.get('data', tr) + conds = [] + for c in tr.get('m_ConditionConstantArray', []): + c = c.get('data', c) + conds.append(f"{tos.get(c.get('m_EventID'), c.get('m_EventID'))} mode={c.get('m_ConditionMode')} th={c.get('m_EventThreshold')}") + dest = tr.get('m_DestinationState') + return dest, conds + + names = [] + for st in states: + st = st.get('data', st) + names.append(tos.get(st.get('m_NameID'), st.get('m_NameID'))) + for i, st in enumerate(states): + st = st.get('data', st) + print(f' [{i}] state "{names[i]}" fullPath="{tos.get(st.get("m_FullPathID"), st.get("m_FullPathID"))}" tag="{tos.get(st.get("m_TagID"), st.get("m_TagID"))}"') + for tr in st.get('m_TransitionConstantArray', []): + dest, conds = describe(tr) + dname = names[dest] if isinstance(dest, int) and 0 <= dest < len(names) else dest + print(f' -> {dname} when {conds}') + for tr in any_tr: + dest, conds = describe(tr) + dname = names[dest] if isinstance(dest, int) and 0 <= dest < len(names) else dest + print(f' AnyState -> {dname} when {conds}') + +missing = wanted - set(found) +if missing: + print('not found:', ', '.join(sorted(missing)))