Merge branch 'skeleton-show-helmet': Skeletons can show their helmet

This commit is contained in:
kanym 2026-10-29 01:23:53 +01:00
commit 373b0069dd
5 changed files with 259 additions and 30 deletions

View file

@ -47,6 +47,7 @@ namespace RacesOfValheim
public static ConfigEntry<bool> HeadFireVFXEnabled;
public static ConfigEntry<bool> BodyModelEnabled;
public static ConfigEntry<bool> RaiseDeadIcon;
public static ConfigEntry<bool> ShowHelmet;
public static void Bind(ConfigFile config)
{
@ -86,6 +87,7 @@ namespace RacesOfValheim
new ConfigDescription("Whether Skeleton players wear the skeleton body. Turn it off if you use a player model mod (EnhancedValheimVRM and the like): Skeletons then keep the vanilla viking body, so the replacement model shows without bones clipping through it. Abilities are unchanged. Client-side, like the option above: it applies to every Skeleton you see, yourself included, and changes nothing for other players."));
RaiseDeadIcon = config.Bind(visuals, "Raise the Dead Icon", true,
new ConfigDescription("Shows the Raise the Dead status icon while your Summon on Kill is on."));
}
ShowHelmet = config.Bind(visuals, "Show Helmet", false,
new ConfigDescription("Off: your helmet stays hidden over the skull. On: the helmet you wear shows. Helmets and hoods are moved and enlarged to fit the skull. Your own choice: other players see you the way you picked. A viking body (Body Model Enabled off) always shows its helmet.")); }
}
}

View file

@ -351,7 +351,7 @@ namespace RacesOfValheim
HideItemInstances(__instance, "m_hairItemInstance");
HideItemInstances(__instance, "m_beardItemInstance");
SetHelmetVisible(__instance, false);
SkeletonVisuals.FitHelmet(p, __instance, SkeletonVisuals.ShowsHelmet(p));
// Poses the mandible, once per frame, after the animation. Attached from
// here rather than from SkeletonRace because this postfix is the one path
@ -396,7 +396,7 @@ namespace RacesOfValheim
ShowItemInstances(__instance, "m_hairItemInstance");
ShowItemInstances(__instance, "m_beardItemInstance");
SetHelmetVisible(__instance, true);
SkeletonVisuals.UnfitHelmet(__instance);
// Parented to rig bones, not to the body container that was just switched
// off above - so without this a human keeps the skeleton's lit sockets.
@ -405,26 +405,6 @@ namespace RacesOfValheim
}
}
/// <summary>
/// A helmet on a skull looks like a helmet floating in a skull, so the race hides it.
///
/// SkeletonRace does this every frame in a world, but it only ever runs for the local
/// player - which is why the helmet came back on the main-menu preview once the body
/// swap started working there. Doing it here covers the menu, remote players and the
/// first frame after a race change, all of which reach this postfix and none of which
/// reach SkeletonRace.
///
/// Delegates to SkeletonVisuals.SetEquipmentPieceHidden, which scales the wrapper to
/// zero and disables its renderers - scale alone leaves a skinned piece (bound to the
/// player's own bones rather than its own transform) still drawing, which is what a
/// helmet with a skinned cloth or chain part looked like.
/// </summary>
private static void SetHelmetVisible(VisEquipment visEq, bool visible)
{
GameObject helmet = Traverse.Create(visEq).Field<GameObject>("m_helmetItemInstance").Value;
SkeletonVisuals.SetEquipmentPieceHidden(helmet, !visible);
}
private static void HideItemInstances(VisEquipment visEq, string fieldName)
{
SetItemInstanceActive(visEq, fieldName, false);

View file

@ -396,10 +396,11 @@ namespace RacesOfValheim
{
// Hide Helmets (Valheim uses singular GameObject for helmet). Only over a skull:
// a viking body wears its helmet, and the VisEquipment postfix puts it back.
// "Show Helmet" keeps it on the skull too, and is published for other clients.
SkeletonVisuals.PublishShowHelmet(Player.m_localPlayer);
if (SkeletonConfig.BodyModelEnabled.Value)
{
var helmetObj = HarmonyLib.Traverse.Create(currentVis).Field<GameObject>("m_helmetItemInstance").Value;
SkeletonVisuals.SetEquipmentPieceHidden(helmetObj, true);
SkeletonVisuals.FitHelmet(Player.m_localPlayer, currentVis, SkeletonConfig.ShowHelmet.Value);
}
// Scale Body Armor (Chest, Legs, Shoulder) by 5%

View file

@ -59,6 +59,41 @@ namespace RacesOfValheim
public static bool ShowsSkeletonBody(Player player) =>
SkeletonConfig.BodyModelEnabled.Value && IsSkeletonPlayer(player);
// The owner's "Show Helmet" choice, so every other client draws this skeleton's helmet the
// way its owner picked rather than the way the onlooker's own setting says.
public const string ShowHelmetZdoKey = "RacesOfValheim_SkeletonShowHelmet";
/// <summary>
/// Whether this skeleton wears its helmet visibly over the skull. The local player and the
/// menu preview (which has no ZDO and is always this client's own character) go by this
/// client's setting; anyone else by what their owner published.
/// </summary>
public static bool ShowsHelmet(Player player)
{
if (player == null) return false;
ZNetView nview = player.GetComponent<ZNetView>();
if (player == Player.m_localPlayer || nview == null || !nview.IsValid())
{
return SkeletonConfig.ShowHelmet.Value;
}
return nview.GetZDO().GetBool(ShowHelmetZdoKey, false);
}
/// <summary>Writes the local player's choice to its ZDO when it differs. Owner only.</summary>
public static void PublishShowHelmet(Player player)
{
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
bool show = SkeletonConfig.ShowHelmet.Value;
if (nview.GetZDO().GetBool(ShowHelmetZdoKey, false) != show)
{
nview.GetZDO().Set(ShowHelmetZdoKey, show);
}
}
/// <summary>
/// Fully hides (or restores) one equipped item instance - a helmet, typically.
///
@ -71,11 +106,11 @@ namespace RacesOfValheim
/// is reasserted the same way (Valheim's own visual refresh re-enables the instance and
/// resets its scale, so both must be redone every time visuals rebuild).
/// </summary>
public static void SetEquipmentPieceHidden(GameObject instance, bool hidden)
public static void SetEquipmentPieceHidden(GameObject instance, bool hidden, float shownSize = 1f)
{
if (instance == null) return;
Vector3 wantedScale = hidden ? Vector3.zero : Vector3.one;
Vector3 wantedScale = hidden ? Vector3.zero : Vector3.one * shownSize;
if (instance.transform.localScale != wantedScale)
{
instance.transform.localScale = wantedScale;
@ -90,6 +125,218 @@ namespace RacesOfValheim
}
}
/// <summary>
/// Where VisEquipment.AttachItem put the helmet: zero, or the prefab's own "equipoffset".
/// Kept on the instance so the fit is always a delta on it, and so taking the fit off
/// puts the helmet back exactly. A re-equip makes a new instance without one.
/// </summary>
private class HelmetBasePose : MonoBehaviour
{
public Vector3 Position;
// Skinned parts whose Head bone was swapped for the fit bone, with the bone list
// AttachItem gave them, so a viking body gets its own head back.
public readonly List<SkinnedMeshRenderer> Fitted = new List<SkinnedMeshRenderer>();
public readonly List<Transform[]> OriginalBones = new List<Transform[]>();
}
private const string FitBoneName = "SkeletonHelmetFitBone";
// The helmet on a skull: metres up and forward, and size. Dialled in on screen with
// Configuration Manager sliders (playtest, 2026-10-29) on the bronze, drake and flametal
// helmets, then written down here; the sliders are gone. One set fits all three bodies.
private const float HelmetFitUp = 0.068f;
private const float HelmetFitForward = -0.053f;
private const float HelmetFitSize = 1.298f;
// The same for the fit bone of skinned helmets (the 16 vanilla prefabs with an
// "attach_skin" child: hoods, but also Padded, Carapace, Sweatband and others). Tuned on
// the Fenring hood, then checked on nearly all the rest (2026-10-29). It scales from the
// Head bone's pivot rather than the helmet joint's, hence the different numbers.
private const float HoodFitUp = 0.041f;
private const float HoodFitForward = -0.071f;
private const float HoodFitSize = 1.246f;
// Which of the helmet joint's own axes are the skull's up and forward. Every player wears
// the same rig, so this is found once and kept. Re-picking it every frame made the
// offset jump sideways whenever the head turned far enough for another axis to win.
private static bool fitAxesFound;
private static Vector3 fitUpAxis, fitForwardAxis;
/// <summary>
/// Picks the axes only while the head faces straight ahead, so a turned head on the
/// first frame cannot lock in the wrong ones. False until then.
/// </summary>
private static bool FindFitAxes(Transform joint, Player player)
{
Vector3 up = ClosestLocalAxis(joint, player.transform.up);
Vector3 forward = ClosestLocalAxis(joint, player.transform.forward);
if (Vector3.Dot(joint.TransformDirection(up), player.transform.up) < 0.8f ||
Vector3.Dot(joint.TransformDirection(forward), player.transform.forward) < 0.8f)
{
return false;
}
fitUpAxis = up;
fitForwardAxis = forward;
fitAxesFound = true;
Jotunn.Logger.LogInfo($"[Skeleton] Helmet fit on '{joint.name}': up = local {up}, forward = local {forward}, joint scale {joint.lossyScale}.");
return true;
}
/// <summary>
/// The helmet on a skull: hidden, or shown and moved to fit the skull, which is bigger
/// and sits higher and further back than the viking head the helmet hangs for. Hidden
/// unless the owner turned on "Show Helmet" (ShowsHelmet).
///
/// Called from the VisEquipment postfix as well as SkeletonRace and ZdoVisualSync:
/// SkeletonRace only ever runs for the local player, which is why the helmet once came
/// back on the main-menu preview. The postfix covers the menu, remote players and the
/// first frame after a race change.
///
/// Up and forward are the player's, carried over to whichever of the helmet joint's own
/// axes points closest to them. The joint turns with the head, so the helmet keeps its
/// place on the skull when the player looks up or down.
///
/// A hood ("attach_skin") is skinned to the player's own bones, so moving its transform
/// does nothing. Its parts weighted to the Head bone get a fit bone instead: a child of
/// the real Head carrying the same kind of move and size. The parts weighted to the neck
/// and shoulders stay put, so the hood stretches between the two like it would over a
/// bigger head. Rigid helmets with a skinned chain or cloth piece get the same treatment
/// for that piece.
/// </summary>
public static void FitHelmet(Player player, VisEquipment vis, bool show)
{
GameObject helmet = vis != null ? HarmonyLib.Traverse.Create(vis).Field<GameObject>("m_helmetItemInstance").Value : null;
if (helmet == null) return;
if (!show)
{
SetEquipmentPieceHidden(helmet, true);
return;
}
// Always the helmet joint, never the instance's parent: a hood hangs off the body
// container, whose axes are not the head's.
Transform joint = HarmonyLib.Traverse.Create(vis).Field<Transform>("m_helmet").Value;
bool rigid = joint != null && helmet.transform.parent == joint;
SetEquipmentPieceHidden(helmet, false, rigid ? HelmetFitSize : 1f);
HelmetBasePose pose = helmet.GetComponent<HelmetBasePose>();
if (pose == null)
{
pose = helmet.AddComponent<HelmetBasePose>();
pose.Position = helmet.transform.localPosition;
}
if (joint == null) return;
if (!fitAxesFound && !FindFitAxes(joint, player)) return;
if (rigid)
{
Vector3 worldOffset = FitOffset(joint, HelmetFitUp, HelmetFitForward);
Vector3 wanted = pose.Position + joint.InverseTransformVector(worldOffset);
if (helmet.transform.localPosition != wanted)
{
helmet.transform.localPosition = wanted;
}
}
FitSkinnedParts(player, helmet, pose, joint);
}
private static Vector3 FitOffset(Transform joint, float up, float forward) =>
joint.TransformDirection(fitUpAxis) * up + joint.TransformDirection(fitForwardAxis) * forward;
private static readonly HashSet<string> loggedCloth = new HashSet<string>();
/// <summary>
/// Points every skinned part of the helmet that uses the Head bone at this player's fit
/// bone, and keeps the fit bone posed. The bone list is the part's own copy (Unity
/// copies on get and on set), so the body and the other armour keep the real Head.
/// </summary>
private static void FitSkinnedParts(Player player, GameObject helmet, HelmetBasePose pose, Transform joint)
{
Animator anim = player.GetComponentInChildren<Animator>();
Transform head = anim != null ? anim.GetBoneTransform(HumanBodyBones.Head) : null;
if (head == null) return;
Transform fitBone = null;
foreach (SkinnedMeshRenderer smr in helmet.GetComponentsInChildren<SkinnedMeshRenderer>(true))
{
if (pose.Fitted.Contains(smr)) continue;
Transform[] bones = smr.bones;
int index = System.Array.IndexOf(bones, head);
if (index < 0) continue;
if (fitBone == null) fitBone = GetFitBone(head);
pose.Fitted.Add(smr);
pose.OriginalBones.Add((Transform[])bones.Clone());
bones[index] = fitBone;
smr.bones = bones;
if (smr.GetComponent<Cloth>() != null && loggedCloth.Add(helmet.name))
{
Jotunn.Logger.LogInfo($"[Skeleton] Helmet '{helmet.name}': skinned part '{smr.name}' carries Cloth; its Head bone was swapped for the fit bone.");
}
}
if (pose.Fitted.Count == 0) return;
if (fitBone == null) fitBone = GetFitBone(head);
Vector3 wantedPos = head.InverseTransformVector(FitOffset(joint, HoodFitUp, HoodFitForward));
Vector3 wantedScale = Vector3.one * HoodFitSize;
if (fitBone.localPosition != wantedPos) fitBone.localPosition = wantedPos;
if (fitBone.localScale != wantedScale) fitBone.localScale = wantedScale;
}
/// <summary>This head's fit bone, made the first time a skinned helmet part needs it.</summary>
private static Transform GetFitBone(Transform head)
{
Transform fitBone = head.Find(FitBoneName);
if (fitBone != null) return fitBone;
fitBone = new GameObject(FitBoneName).transform;
fitBone.SetParent(head, false);
fitBone.localRotation = Quaternion.identity;
return fitBone;
}
/// <summary>Shows the helmet where vanilla put it, undoing any fit. For a viking body.</summary>
public static void UnfitHelmet(VisEquipment vis)
{
GameObject helmet = vis != null ? HarmonyLib.Traverse.Create(vis).Field<GameObject>("m_helmetItemInstance").Value : null;
if (helmet == null) return;
SetEquipmentPieceHidden(helmet, false);
HelmetBasePose pose = helmet.GetComponent<HelmetBasePose>();
if (pose == null) return;
if (helmet.transform.localPosition != pose.Position)
{
helmet.transform.localPosition = pose.Position;
}
for (int i = 0; i < pose.Fitted.Count; i++)
{
if (pose.Fitted[i] != null) pose.Fitted[i].bones = pose.OriginalBones[i];
}
pose.Fitted.Clear();
pose.OriginalBones.Clear();
}
private static Vector3 ClosestLocalAxis(Transform joint, Vector3 worldDir)
{
Vector3 local = joint.InverseTransformDirection(worldDir);
Vector3 abs = new Vector3(Mathf.Abs(local.x), Mathf.Abs(local.y), Mathf.Abs(local.z));
if (abs.x >= abs.y && abs.x >= abs.z) return new Vector3(Mathf.Sign(local.x), 0f, 0f);
if (abs.y >= abs.z) return new Vector3(0f, Mathf.Sign(local.y), 0f);
return new Vector3(0f, 0f, Mathf.Sign(local.z));
}
/// <summary>
/// The tier a given player's body should be built for. The ZDO carries it so remote
/// players render at their own standing; without one - the menu preview - fall back to

View file

@ -127,11 +127,10 @@ namespace RacesOfValheim
vis.SetHairItem(0);
vis.SetBeardItem(0);
// Hide Helmet
// Hide Helmet, unless its owner chose to show it
if (SkeletonConfig.BodyModelEnabled.Value)
{
var helmetObj = HarmonyLib.Traverse.Create(vis).Field<GameObject>("m_helmetItemInstance").Value;
SkeletonVisuals.SetEquipmentPieceHidden(helmetObj, true);
SkeletonVisuals.FitHelmet(m_player, vis, SkeletonVisuals.ShowsHelmet(m_player));
}
// Scale Body Armor