New "Show Helmet" option under Skeleton - Visuals, off by default. The owner's choice is written to the ZDO, so other players see the helmet the way its owner picked. On a skull the helmet moves up and back and grows to fit, since the skull is bigger than the viking head the helmet hangs for. Hoods and the other skinned helmets can't be moved by their transform: their Head bone is swapped for a fitted child bone, so the head part follows the skull and the shoulder parts stay put. A viking body gets the vanilla placement and bones back.
778 lines
38 KiB
C#
778 lines
38 KiB
C#
using System.Collections.Generic;
|
|
using Jotunn.Managers;
|
|
using UnityEngine;
|
|
|
|
namespace RacesOfValheim
|
|
{
|
|
/// <summary>
|
|
/// The Skeleton's cosmetics that any client can grow for itself.
|
|
///
|
|
/// The head flame started life inside SkeletonRace, which is a single MonoBehaviour that only
|
|
/// ever looks at Player.m_localPlayer - so the fire existed on one client, on one player, and
|
|
/// everyone else saw a bare skull. Same shape of bug as the Draugh's aura, and the same fix:
|
|
/// the build takes a Player, and each client grows a copy for every skeleton it can see.
|
|
///
|
|
/// Nothing here is networked and nothing needs to be. The tier is already on the ZDO, so every
|
|
/// client can work out for itself whether a given skeleton should be alight.
|
|
/// </summary>
|
|
public static class SkeletonVisuals
|
|
{
|
|
public const string RaceId = "Skeleton";
|
|
|
|
/// <summary>
|
|
/// Reads the race off the ZDO, falling back to m_customData.
|
|
///
|
|
/// The fallback is what makes the race show up on the main-menu character preview.
|
|
/// FejdStartup.SetupCharacterPreview instantiates a Player and calls
|
|
/// PlayerProfile.LoadPlayerData on it, which restores m_customData - so the preview does
|
|
/// know it is a Skeleton. What it has no business having is a ZNetView, and reading the
|
|
/// race from the ZDO alone meant the body swap gave up before it ever looked.
|
|
/// </summary>
|
|
public static string GetPlayerRace(Player player)
|
|
{
|
|
if (player == null) return "Human";
|
|
|
|
ZNetView nview = player.GetComponent<ZNetView>();
|
|
if (nview != null && nview.IsValid())
|
|
{
|
|
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "");
|
|
if (!string.IsNullOrEmpty(race)) return race;
|
|
}
|
|
|
|
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string custom))
|
|
{
|
|
return custom;
|
|
}
|
|
|
|
return "Human";
|
|
}
|
|
|
|
public static bool IsSkeletonPlayer(Player player) => GetPlayerRace(player) == RaceId;
|
|
|
|
/// <summary>
|
|
/// Whether this client draws the skeleton's bones on this player. False for every
|
|
/// non-Skeleton, and for every Skeleton when "Body Model Enabled" is off: model-replacement
|
|
/// mods (EnhancedValheimVRM and the like) hide the vanilla body and draw their own, so the
|
|
/// borrowed bones ended up floating around the replacement model. With the option off the
|
|
/// Skeleton keeps every ability and only looks like a plain viking.
|
|
/// </summary>
|
|
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.
|
|
///
|
|
/// Scale-to-zero alone leaves skinned pieces behind: a SkinnedMeshRenderer bound to the
|
|
/// player's own bones (some helmets carry a cloth or chain piece skinned that way) is
|
|
/// deformed by those bone matrices, not by its GameObject's transform, so zeroing the
|
|
/// wrapper's localScale does nothing to it - exactly the "part of the helmet is still
|
|
/// there" artifact reported on the Skeleton. Disabling every Renderer underneath has no
|
|
/// such exception; combined with the scale it hides both plain and skinned pieces, and
|
|
/// 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, float shownSize = 1f)
|
|
{
|
|
if (instance == null) return;
|
|
|
|
Vector3 wantedScale = hidden ? Vector3.zero : Vector3.one * shownSize;
|
|
if (instance.transform.localScale != wantedScale)
|
|
{
|
|
instance.transform.localScale = wantedScale;
|
|
}
|
|
|
|
foreach (Renderer renderer in instance.GetComponentsInChildren<Renderer>(true))
|
|
{
|
|
if (renderer.enabled == hidden)
|
|
{
|
|
renderer.enabled = !hidden;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <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
|
|
/// whatever this client can work out, which in the menu is the base tier, since there is
|
|
/// no world loaded to have killed anything.
|
|
/// </summary>
|
|
public static int GetProgressionState(Player player)
|
|
{
|
|
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
|
|
if (nview != null && nview.IsValid())
|
|
{
|
|
return nview.GetZDO().GetInt("RacesOfValheim_SkeletonState", 0);
|
|
}
|
|
|
|
return BossProgressionManager.GetCurrentProgressionState();
|
|
}
|
|
|
|
public const string LookZdoKey = "RacesOfValheim_SkeletonLook";
|
|
public const string LookDataKey = "SkeletonLook";
|
|
|
|
/// <summary>
|
|
/// The body this player chose at the barber, "" if they never did. Read the same way as
|
|
/// the race: the ZDO for anyone on the network, m_customData for the menu preview.
|
|
/// </summary>
|
|
public static string GetLook(Player player)
|
|
{
|
|
if (player == null) return "";
|
|
|
|
ZNetView nview = player.GetComponent<ZNetView>();
|
|
if (nview != null && nview.IsValid())
|
|
{
|
|
return nview.GetZDO().GetString(LookZdoKey, "");
|
|
}
|
|
|
|
if (player.m_customData != null && player.m_customData.TryGetValue(LookDataKey, out string look))
|
|
{
|
|
return look;
|
|
}
|
|
|
|
return "";
|
|
}
|
|
|
|
/// <summary>The model prefab to wear for this player at this tier, look applied.</summary>
|
|
public static string GetModel(Player player, int state)
|
|
{
|
|
return SkeletonProgression.ResolveModel(state, GetLook(player));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Fire sources in preference order. BUILDING PIECES ONLY, and that is the bug fix.
|
|
///
|
|
/// This list used to start with "Torch", which is the ITEM prefab, and an item in Valheim
|
|
/// is a live world object: ItemDrop, a Rigidbody and a ZNetView, all of them on the same
|
|
/// node the fire particles are on. That the borrow was reaching that node and not a bare
|
|
/// flame was already known here - the strip below used to name "the stick mesh, ItemDrop,
|
|
/// durability", and the Rigidbody it had to destroy was the one that made an early version
|
|
/// of the clone visibly fall away from the skull.
|
|
///
|
|
/// What was missed is that the copy was made into a holder that was ALREADY SWITCHED ON,
|
|
/// so all of it woke up for a frame before the strip could take any of it off - and a woken
|
|
/// ZNetView is not a cosmetic mistake. ZNetView.Awake with no init ZDO calls
|
|
/// ZDOMan.CreateNewZDO at the object's position, marks it persistent, stamps it with the
|
|
/// prefab hash and registers it with the scene; ZNetView.OnDestroy does none of that in
|
|
/// reverse - it only releases asset references. So every rebuild of the flame left the
|
|
/// world holding a persistent "there is a Torch here" record that nothing was drawing,
|
|
/// saved with everything else, and the next time that zone was built from the save every
|
|
/// client spawned the torch. That is the whole of the report: a torch dropped on logging
|
|
/// in and out, and a portal handing it to everyone.
|
|
///
|
|
/// A ground torch is a building piece. It has the same fire (both carry fx_Torch_Basic) and
|
|
/// no item behaviour at all, so there is nothing on it to bring across by accident. The
|
|
/// inactive holder in Build and the two filters below are the lines of defence behind that,
|
|
/// for whatever a future source turns out to carry.
|
|
/// </summary>
|
|
private static readonly string[] FlameSourcePrefabs =
|
|
{
|
|
"piece_groundtorch_wood", "piece_groundtorch", "fire_pit"
|
|
};
|
|
|
|
/// <summary>
|
|
/// Particle systems that are not fire. Matched on the object name, which is how these are
|
|
/// named in the prefabs that carry them - an item's pickup glitter above all, which is a
|
|
/// ParticleSystem like any other and was worn on the skull along with the flame.
|
|
/// </summary>
|
|
private static readonly string[] NotFire =
|
|
{
|
|
"sparkle", "sparcle", "glitter", "pickup", "shine", "twinkle"
|
|
};
|
|
|
|
private static bool IsFire(GameObject candidate)
|
|
{
|
|
string name = candidate.name.ToLower();
|
|
foreach (string word in NotFire)
|
|
{
|
|
if (name.Contains(word)) return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// Said once per particle name per session, with everything the borrowed node carries that
|
|
// is not a particle. The point is that the next time something rides along, the log names
|
|
// it - this bug cost a bug report because nothing ever said "that flame is an item".
|
|
private static readonly HashSet<string> loggedParticles = new HashSet<string>();
|
|
|
|
private static void LogClonedOnce(GameObject source)
|
|
{
|
|
if (!loggedParticles.Add(source.name)) return;
|
|
|
|
List<string> passengers = new List<string>();
|
|
foreach (Component comp in source.GetComponentsInChildren<Component>(true))
|
|
{
|
|
if (comp == null || IsPureVfx(comp, true)) continue;
|
|
passengers.Add(comp.GetType().Name);
|
|
}
|
|
|
|
Jotunn.Logger.LogInfo(
|
|
$"[Skeleton] Head flame: cloned '{source.name}'" +
|
|
(passengers.Count == 0 ? "." : ", stripped " + string.Join(", ", passengers.ToArray()) + "."));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Says what a borrowed-by-name prefab actually resolved to: which object, where it sits in
|
|
/// ITS OWN hierarchy, and the material and shader the first particle on it carries. Once per
|
|
/// name per session, so it costs a handful of lines and answers the question that took a
|
|
/// bundle extractor to answer the first time.
|
|
///
|
|
/// READ THE root FLAG FIRST. A root-level object is a real prefab and almost certainly the
|
|
/// vanilla one. A parented one is a child node that Jotunn's cache picked up because nothing
|
|
/// better in memory answered to that name - which is what happens when the name does not
|
|
/// exist in vanilla at all, and is exactly how another mod's weapon trail ended up worn as
|
|
/// this race's fire aura. See EnsureFireAura.
|
|
/// </summary>
|
|
private static readonly HashSet<string> loggedResolutions = new HashSet<string>();
|
|
|
|
public static void LogResolvedPrefabOnce(string wanted, GameObject resolved)
|
|
{
|
|
if (!loggedResolutions.Add(wanted)) return;
|
|
|
|
if (resolved == null)
|
|
{
|
|
Jotunn.Logger.LogWarning($"[Skeleton] Prefab lookup '{wanted}' resolved to NOTHING.");
|
|
return;
|
|
}
|
|
|
|
string path = resolved.name;
|
|
for (Transform t = resolved.transform.parent; t != null; t = t.parent)
|
|
{
|
|
path = t.name + "/" + path;
|
|
}
|
|
|
|
ParticleSystem first = resolved.GetComponentInChildren<ParticleSystem>(true);
|
|
ParticleSystemRenderer psr = first != null ? first.GetComponent<ParticleSystemRenderer>() : null;
|
|
Material material = psr != null ? psr.sharedMaterial : null;
|
|
|
|
Jotunn.Logger.LogInfo(
|
|
$"[Skeleton] Prefab lookup '{wanted}' resolved to '{path}' " +
|
|
$"(root={resolved.transform.parent == null}) " +
|
|
$"particle='{(first != null ? first.name : "none")}' " +
|
|
$"material='{(material != null ? material.name : "none")}' " +
|
|
$"shader='{(material != null && material.shader != null ? material.shader.name : "none")}' " +
|
|
$"startColor={(first != null ? first.main.startColor.color.ToString() : "-")}");
|
|
}
|
|
|
|
private static GameObject cachedFlameSource;
|
|
private static bool flameSourceResolved;
|
|
|
|
/// <summary>
|
|
/// Finds a vanilla prefab that carries real fire particles. Resolved once per session,
|
|
/// failure included, so a miss cannot turn into a per-frame log.
|
|
/// </summary>
|
|
private static GameObject ResolveFlameSource()
|
|
{
|
|
if (flameSourceResolved) return cachedFlameSource;
|
|
flameSourceResolved = true;
|
|
|
|
foreach (string name in FlameSourcePrefabs)
|
|
{
|
|
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(name);
|
|
if (prefab == null) continue;
|
|
|
|
bool hasFire = false;
|
|
foreach (ParticleSystem ps in prefab.GetComponentsInChildren<ParticleSystem>(true))
|
|
{
|
|
if (IsFire(ps.gameObject)) { hasFire = true; break; }
|
|
}
|
|
if (!hasFire) continue;
|
|
|
|
Jotunn.Logger.LogInfo($"[Skeleton] Head flame source resolved to '{name}'.");
|
|
cachedFlameSource = prefab;
|
|
return cachedFlameSource;
|
|
}
|
|
|
|
Jotunn.Logger.LogWarning(
|
|
"[Skeleton] No fire prefab resolved (" + string.Join(", ", FlameSourcePrefabs) +
|
|
"); the skull stays unlit.");
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Strips a borrowed subtree down to what a pure VFX needs, and nothing else.
|
|
///
|
|
/// Allowlist, not a blocklist: keep the particle systems, their renderers and the lights
|
|
/// (and the loose meshes, for the eye glow), destroy every other component whatever it
|
|
/// turns out to be. A blocklist of "known bad" types (MonoBehaviour, Collider) missed
|
|
/// Rigidbody - not a MonoBehaviour in Unity - and a fire node carrying one meant physics
|
|
/// kept acting on the clone independently of the holder being repositioned every frame.
|
|
///
|
|
/// DestroyImmediate rather than Destroy, because the caller is about to switch the holder
|
|
/// on and Destroy does not take effect until the end of the frame - by which time every
|
|
/// script it was supposed to remove would have had its Awake.
|
|
///
|
|
/// Repeated passes, because Unity refuses to destroy a component another one still
|
|
/// requires ("Can't remove Humanoid because CharacterDrop depends on it"): the dependent
|
|
/// goes on one pass and the component it held down goes on the next. Behaviours first
|
|
/// within each pass, for the same reason.
|
|
/// </summary>
|
|
public static void StripToVfx(GameObject root, bool keepMeshes, string label)
|
|
{
|
|
if (root == null) return;
|
|
|
|
for (int pass = 0; pass < 4; pass++)
|
|
{
|
|
bool anyLeft = false;
|
|
|
|
foreach (MonoBehaviour behaviour in root.GetComponentsInChildren<MonoBehaviour>(true))
|
|
{
|
|
if (behaviour == null) continue;
|
|
Object.DestroyImmediate(behaviour);
|
|
}
|
|
|
|
foreach (Component comp in root.GetComponentsInChildren<Component>(true))
|
|
{
|
|
if (comp == null || IsPureVfx(comp, keepMeshes)) continue;
|
|
Object.DestroyImmediate(comp);
|
|
anyLeft = true;
|
|
}
|
|
|
|
if (!anyLeft) return;
|
|
}
|
|
|
|
// Four passes and something is still holding on. Say what it is: a survivor here is the
|
|
// exact shape of bug this whole class exists to prevent, and it is about to be woken.
|
|
foreach (Component comp in root.GetComponentsInChildren<Component>(true))
|
|
{
|
|
if (comp == null || IsPureVfx(comp, keepMeshes)) continue;
|
|
Jotunn.Logger.LogWarning(
|
|
$"[{label}] '{comp.GetType().Name}' on '{comp.gameObject.name}' could not be stripped " +
|
|
"off the borrowed effect; it will run on the player.");
|
|
}
|
|
}
|
|
|
|
private static bool IsPureVfx(Component comp, bool keepMeshes)
|
|
{
|
|
if (comp is Transform || comp is ParticleSystem || comp is ParticleSystemRenderer || comp is Light)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
return keepMeshes && (comp is MeshRenderer || comp is MeshFilter);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Clones one node of a vanilla prefab as pure VFX and hangs it under <paramref name="parent"/>.
|
|
///
|
|
/// The temporary holder is created INACTIVE and the copy is made inside it. That single
|
|
/// line is the point of this method: Unity does not run Awake on an object that is not
|
|
/// active in its hierarchy, so ItemDrop, ZNetView, Rigidbody and every script on the
|
|
/// borrowed node are destroyed before any of them ever exists as far as the game is
|
|
/// concerned. Stripping AFTER the copy is already live - which is what the head flame and
|
|
/// the eye glow both used to do - is a frame too late, and one frame is all a ZNetView
|
|
/// needs to write a persistent object into the save. Same lesson, same fix, as ModelBorrow.
|
|
///
|
|
/// The copy is handed back parented to <paramref name="parent"/> and switched on, with its
|
|
/// pose left to the caller.
|
|
/// </summary>
|
|
public static GameObject BorrowEffect(GameObject source, Transform parent, string cloneName,
|
|
bool keepMeshes, string label)
|
|
{
|
|
if (source == null || parent == null) return null;
|
|
|
|
GameObject holder = new GameObject("BorrowedEffectHolder");
|
|
holder.SetActive(false); // BEFORE the Instantiate below.
|
|
|
|
GameObject copy = Object.Instantiate(source, holder.transform);
|
|
copy.name = cloneName;
|
|
|
|
StripToVfx(copy, keepMeshes, label);
|
|
|
|
copy.transform.SetParent(parent, false);
|
|
Object.DestroyImmediate(holder);
|
|
|
|
// A prefab can leave its own effects switched off for a script to turn on later, and
|
|
// that script is exactly what was just destroyed.
|
|
copy.SetActive(true);
|
|
foreach (Light light in copy.GetComponentsInChildren<Light>(true)) light.enabled = true;
|
|
foreach (Renderer renderer in copy.GetComponentsInChildren<Renderer>(true)) renderer.enabled = true;
|
|
|
|
return copy;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The fire aura's visual, and the reason it now has none.
|
|
///
|
|
/// The aura itself (SkeletonRace.ApplyFireAura) burns everything inside FireAuraRadius from
|
|
/// Moder on and is untouched. What is gone is the way it used to try to show itself:
|
|
///
|
|
/// PrefabManager.Cache.GetPrefab<GameObject>("vfx_smoke")
|
|
/// ?? PrefabManager.Cache.GetPrefab<GameObject>("vfx_surtling_death")
|
|
///
|
|
/// NEITHER NAME EXISTS IN VALHEIM. Checked against the game's own asset manifest: there is no
|
|
/// vfx_smoke, and no surtling death effect under any spelling. In a plain install both
|
|
/// lookups came back null, no particle system was ever added, and this aura has never been
|
|
/// visible to anybody since the day it was written.
|
|
///
|
|
/// A dead branch would be harmless if the lookup were harmless. It is not. PrefabManager.Cache
|
|
/// is, in Jotunn's own words, a "global cache of Unity Objects by asset name" built with
|
|
/// Resources.FindObjectsOfTypeAll, so it answers with anything in memory - including the
|
|
/// contents of every other mod's asset bundle - and its tie-break for a duplicate name ends
|
|
/// in "the newly discovered object replaces the cached one". A name vanilla does not use has
|
|
/// no vanilla candidate to beat, which leaves it a free slot for whoever ships one.
|
|
///
|
|
/// Somebody shipped one. With Magic_Supremacy installed the lookup resolved to
|
|
/// 'EncounterCreatureRikoMountain_DO/vfx_smoke' - a CHILD node of one of that mod's
|
|
/// creatures, carrying the material 'club_trail_riko_DO' on the shader
|
|
/// 'Dreanegade/ParticleAlphaEmission'. A weapon trail, on an emissive shader, sprayed through
|
|
/// a 4.5m sphere centred on the player: the purple smoke around the burning skull this race
|
|
/// was reported for, on every client that could see the skeleton.
|
|
///
|
|
/// So the aura is invisible deliberately now, which costs it nothing it ever had. To give it
|
|
/// a look, build it the way HeadFlame does: resolve a prefab under a name vanilla really uses
|
|
/// (ResolveFlameSource already holds one that works) and clone it through BorrowEffect,
|
|
/// instead of hand-rolling a particle system around a material taken by name.
|
|
/// </summary>
|
|
public static void EnsureFireAura(Player player, bool enable, ref GameObject aura)
|
|
{
|
|
// Nothing is built, so there is nothing to switch on either way - but a leftover is
|
|
// destroyed rather than left riding the player, which is what a session that swapped
|
|
// this assembly in mid-flight would otherwise be stuck with.
|
|
if (aura == null) return;
|
|
|
|
Object.Destroy(aura);
|
|
aura = null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// One player's burning skull. Cosmetic only - it deals nothing and blocks nothing.
|
|
///
|
|
/// Held per player rather than statically: a static would hand the second skeleton in view
|
|
/// the first one's fire. Call Apply every frame; it builds once and then only follows.
|
|
/// </summary>
|
|
public class HeadFlame
|
|
{
|
|
// Above the head bone's own origin, which sits at the base of the skull.
|
|
private const float Height = 0.18f;
|
|
|
|
// Torch flames are authored for a fist-sized fire on a stick, so the skull wears a big
|
|
// multiple of one.
|
|
private const float Scale = 1.8f;
|
|
|
|
private GameObject m_instance;
|
|
private Transform m_headBone;
|
|
|
|
public void Apply(Player player, bool enable)
|
|
{
|
|
if (!enable)
|
|
{
|
|
if (m_instance != null && m_instance.activeSelf) m_instance.SetActive(false);
|
|
return;
|
|
}
|
|
|
|
if (player == null) return;
|
|
|
|
if (m_instance == null && !Build(player)) return;
|
|
|
|
if (!m_instance.activeSelf) m_instance.SetActive(true);
|
|
|
|
// Follows the skull without inheriting its scale.
|
|
if (m_headBone != null)
|
|
{
|
|
m_instance.transform.position = m_headBone.position + Vector3.up * Height;
|
|
}
|
|
}
|
|
|
|
/// <summary>Returns false while the pieces it needs are not ready yet.</summary>
|
|
private bool Build(Player player)
|
|
{
|
|
Animator anim = player.GetComponentInChildren<Animator>();
|
|
m_headBone = anim != null ? anim.GetBoneTransform(HumanBodyBones.Head) : null;
|
|
if (m_headBone == null) return false; // rig not up yet; try again next frame
|
|
|
|
GameObject source = ResolveFlameSource();
|
|
if (source == null) return false; // already logged once by the resolver
|
|
|
|
// Deliberately not parented to the head bone: the player rig is authored at
|
|
// roughly 100x, and a particle system inheriting that would put a bonfire where a
|
|
// candle belongs. It hangs off the player and is moved onto the bone each frame.
|
|
m_instance = new GameObject("SkeletonHeadFlameVFX");
|
|
m_instance.transform.SetParent(player.transform, false);
|
|
m_instance.transform.localScale = Vector3.one * Scale;
|
|
|
|
// Real fire is cloned rather than built by hand. The first attempt at this made a
|
|
// particle system from scratch on the smoke material, and a hand-rolled gradient
|
|
// over a smoke sprite reads as a wisp, not a burning skull.
|
|
//
|
|
// Every clone goes through BorrowEffect, which builds it inactive and strips it
|
|
// before it can wake. Nothing from the source prefab - a script, a Rigidbody, a
|
|
// ZNetView - ever gets a frame of life on the player.
|
|
foreach (ParticleSystem ps in source.GetComponentsInChildren<ParticleSystem>(true))
|
|
{
|
|
if (!IsFire(ps.gameObject)) continue;
|
|
|
|
GameObject copy = BorrowEffect(ps.gameObject, m_instance.transform,
|
|
ps.gameObject.name, false, "Skeleton");
|
|
if (copy == null) continue;
|
|
|
|
LogClonedOnce(ps.gameObject);
|
|
|
|
copy.transform.localPosition = Vector3.zero;
|
|
copy.transform.localRotation = Quaternion.identity;
|
|
|
|
// So the holder's scale actually enlarges the fire rather than just spreading
|
|
// out where the particles spawn.
|
|
ParticleSystem.MainModule main = copy.GetComponent<ParticleSystem>().main;
|
|
main.scalingMode = ParticleSystemScalingMode.Hierarchy;
|
|
}
|
|
|
|
// A torch's own light is tuned to light a corridor from waist height; on a head it
|
|
// blows out the whole face. Keep the glow, lose the floodlight.
|
|
foreach (Light light in m_instance.GetComponentsInChildren<Light>(true))
|
|
{
|
|
light.range *= 0.5f;
|
|
light.intensity *= 0.6f;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
}
|